Jump to content


Photo

array recreation?


  • Please log in to reply
1 reply to this topic

#1 chawezul

chawezul
  • Members
  • PipPip
  • Member
  • 19 posts
  • LocationSomewhere, for sure

Posted 22 May 2006 - 04:38 AM

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:

$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);
}


#2 samshel

samshel
  • Members
  • PipPipPip
  • Advanced Member
  • 837 posts

Posted 22 May 2006 - 06:39 AM

Try putting this line in the function function findprimes($n, $p) {

global $result;

hth
Cheers,
SamShel
-----------------------------------------------
--: FUTURE IS LINUX :--
-----------------------------------------------




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users