As a programming exercise, I decided to make a prime factoring function using recursion:
static bool isPrime(int n)
{
if (n < 2)
return false;
if (n % 2 == 0)
return (n == 2);
int root = (int)Math.Sqrt((double)n);
for (int i = 3; i <= root; i += 2)
if (n % i == 0) return false;
return true;
}
static bool iseven(int n)
{
return n % 2 == 0;
}
static int[] prfact(int n, int curr, List<int> nums)
{
if (nums.All(x => isPrime(x)) && isPrime(curr))
{
nums.Add(curr);
return nums.ToArray();
}
else if (iseven(curr))
{
nums.Add(2);
return prfact(n, curr / 2, nums);
}
else if (!iseven(curr))
{
int div = 3;
while (curr % div != 0 || !isPrime(div))
div += 2;
nums.Add(div);
return prfact(n, curr / div, nums);
}
else
return null;
}
static int[] factor(int n)
{
return prfact(n, n, new List<int>());
}
How efficient is it and how can it be improved?