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;
        }
    }
}


 

Posted on Saturday, February 27, 2010 3:11 PM | Back to top


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

# re: C# - Quickly determining the Factors of a given number
Requesting Gravatar...
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

# re: C# - Quickly determining the Factors of a given number
Requesting Gravatar...
You're absolutely correct - forgot to change some variable names when I was pulling this out of my euler problem to make it more generic - went ahead and corrected it.

Thanks for the catch!
Left by Bob Palmer on Mar 02, 2010 7:25 PM

Your comment:
 (will show your gravatar)


Copyright © BobPalmer | Powered by: GeeksWithBlogs.net