Jump to content

Recommended Posts

Ok, here's my problem, I want my function to return an array of numbers that are the prime factors of the input number. My code works. It's all good. Everything is great. Except, the array that is returned is only ONE item long, and it is the last item in the array. So my assumption is that everytime it calls to add to the array, it simply empties the array (or recreates it) and then adds the item. If you can help me that'd be great!

Code:

[code]$result = Array();

function prime($n, $y) {
    if ($y == 1) return true;
    elseif (($n % $y) == 0) return false;
    else return prime($n, $y-1);
}

function findprimes($n, $p) {
    if (! (prime($p, $p-1))) return findprimes($n, $p+1);
    elseif ($n == $p) { $result[] = $n; return $result; }
    elseif (($n % $p) == 0) { $result[] = $p; return findprimes($n/$p, $p); }
    else return findprimes($n, $p+1);
}

function primefactors($n) {
    return findprimes($n, 2);
}[/code]
Link to comment
https://forums.phpfreaks.com/topic/10164-array-recreation/
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.