patterncsharpMinor
Prime factoring function using recursion
Viewed 0 times
recursionfunctionfactoringusingprime
Problem
As a programming exercise, I decided to make a prime factoring function using recursion:
How efficient is it and how can it be improved?
static bool isPrime(int n)
{
if (n 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());
}How efficient is it and how can it be improved?
Solution
- +1 for stopping your
isPrimesearch at the SqRt(n). That's a nice little optimization.
- +1 for incrementing by 2. It's nice to see you realized that since it wasn't possibly even by this point, that you could optimize.
- Next, consider a sieve or memento implementation for further performance improvements on
isPrime.
- Consider renaming
roottolimit.
- +1 for extracting an
isEvenmethod.
- -1 for neglecting to use it in your
isPrimemethod.
- Instead of having
prfactandfactor, Renameprfacttofactor, overloading the latter. Make itprivatescoped to hide the implementation details from the outside world.
Sorry for the mostly non-algo review. Not my strong suit & short on time.
Context
StackExchange Code Review Q#146093, answer score: 5
Revisions (0)
No revisions yet.