3Sep/130
Calculate the Factors of a number
This is a C sharp implementation of the method used to calculate the factors of the number, as described at Wikihow.com. It can come in quite handy when working with Project Euler.
/// <summary> /// Calculate the Factors of a number /// </summary> /// <param name="n">Number to examine</param> /// <returns>List of factors</returns> static List<int> FactorNumber(int n) { List<int> div = new List<int>(); int p=2; do { if (n == 1) break; while (n % p !=0) p++; do { n /= p; div.Add(p); } while (n % p == 0); } while (true); return div; }
Usage is simple enough:
List<int> factor = FactorNumber(6552); //returns 2,2,2,3,3,7,13 factor = FactorNumber(17); //returns 17 factor = FactorNumber(25); //returns 5,5 factor = FactorNumber(60); //returns 2,2,3,5 factor = FactorNumber(100); //returns 2,2,5,5 factor = FactorNumber(45360); //returns 2,2,2,2,3,3,3,3,5,7
Leave a comment