HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Prime factoring function using recursion

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
recursionfunctionfactoringusingprime

Problem

As a programming exercise, I decided to make a prime factoring function using recursion:

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 isPrime search 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 root to limit.



  • +1 for extracting an isEven method.



  • -1 for neglecting to use it in your isPrime method.



  • Instead of having prfact and factor, Rename prfact to factor, overloading the latter. Make it private scoped 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.