13. Prime factors

The most obvious approach to prime factoring a number is to loop through values less than that number and see if they divide into that number evenly. Each time you find such a factor, you divide it from the number. You continue this process until the modified number equals 1.

The following method uses this approach:

// Divide by smaller values up the the square root of the value.private List<long> Method1(long number){    checked    {        List<long> factors = new List<long>();        // Pull out 2s.        while (number % 2 == 0)        {            factors.Add(2);            number /= 2;        }        // Pull out odd factors.        long limit = (long)Math.Sqrt(number);        for (long factor = 3; factor <= limit; factor += 2)        {            while (number % factor == 0)            {                factors.Add(factor); number /= factor; ...

Get The Modern C# Challenge now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.