»
S
I
D
E
B
A
R
«
Finding all factors of a given number in C#
November 22nd, 2009 by admin

To find all factors of a given number in C# can be done using many different ways. A lean way of doing so is:

  • Loop from 1 to the square root of the number, call the index “i”.
  • if number mod i is 0, add i and number / i to the list of factors.
public List<int> Factor(int number) {
    List<int> factors = new List<int>();
    int max = (int)Math.Sqrt(number);  //round down
    for(int factor = 1; factor <= max; ++factor) { //test from 1 to the square root, or the int below it, inclusive.
        if(number % factor == 0) {
            factors.add(factor);
            if(factor != max) { // Don't add the square root twice!  Thanks Jon
                factors.add(number/factor);
            }
        }
    }
    return factors;
}

There are many other ways you could explore. You could implement this as an IEnumerable<int> as well – use yield instead of adding to a list. The advantage with List<int> is that it could be sorted before return if required. Then again, you could get a sorted enumerator with a hybrid approach, yielding the first factor and storing the second one in each iteration of the loop, then yielding each value that was stored in reverse order.

You will also want to do something to handle the case where a negative number passed into the function.

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay



Similar Posts:
Leave a Reply

Powered by WP Hashcash

»  Substance: WordPress   »  Style: Ahren Ahimsa