21 December 2013

Get factors of a number

int n = 10;
List<int> factors = new List<int>();
int max = Convert.ToInt32(Math.Sqrt(n));
for (int i = 1; i <= max; i++)
{
if (n % i == 0)
{
factors.Add(i);
if (i != max) // add square-root factors only once.
factors.Add(n / i);
}
}

No comments: