Geeks With Blogs
Bob Palmer's Developer Blog .NET, SQL, and Silverlight Development

This is another quick code snippet to help those working through Project Euler problems.  A very common part of a problem involves factors or the counting of factors.  This snippet below will make quick work of getting a list of a given integer's factors.

Enjoy!

private static IEnumerable<int> GetFactors(int num)
{
//Given anumber (num), return a list of all of it's
//factors.
//We're going to grab this from both ends, since a given factor
//divided by our number will yield a second factor. for example,
//the factors of 6 can be expressed as:
// Given our first factor (1), and dividing 1 / 6, we get a second factor (6).
// Given our third factor (2), and dividing 2 / 6, we get a fourth factor (3).
for (int factor = 1; factor * factor <= num; factor++)
{
if (num % factor == 0)
{
yield return factor;
if (factor * factor != num)
yield return num / factor;
}
}
}

Comments on this post: C# - Quickly determining the Factors of a given number

# re: C# - Quickly determining the Factors of a given number One minor quibble:

maxnum is never defined anywhere. Is it an input parameter, or just an int?
Left by BigJim on Mar 01, 2010 12:53 PM