Jump to content

array recreation?


chawezul

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.