Evil Science A whole load of stuff


Calculate the divisors of a number

Here are two different ways of calculating the divisors of a number using C#, something you're going to find extremely helpful when tackling Project Euler.

This method uses a for loop and a generic list.

static List<int> GetDivisors(int n)
    List<int> div = new List<int>();
    for (int ctr = n / 2; ctr > 0; ctr--)
        if (n % ctr == 0)

    return div;

This one uses an Enumerable Range and LINQ, and returns the results as a generic list.

int n = 6556;
List<int> div =
Enumerable.Range(1, n / 2).Where(i => n % i == 0).Union(new List<int>{n}).ToList();

//returns 48 results


Comments (0) Trackbacks (0)

No comments yet.

Leave a comment

No trackbacks yet.