I have an associative array, ie
$primes = array(
2=>2,
3=>3,
5=>5,
7=>7,
11=>11,
13=>13,
17=>17,
// ...etc
);
then I do
// seek to first prime greater than 10000
reset($primes);
while(next($primes) < 10000) {}
prev($primes);
// iterate until target found
while($p = next($primes)) {
$res = doSomeCalculationsOn($p);
if( IsPrime($res) )
return $p;
}
The problem is that IsPrime also loops through the $primes array,
function IsPrime($num) {
global $primesto, $primes, $lastprime;
if ($primesto >= $num)
// using the assoc array lets me do this as a lookup
return isset($primes[$num]);
$root = (int) sqrt($num);
if ($primesto < $root)
CalcPrimesTo($root);
foreach($primes as $p) { // <- Danger, Will Robinson!
if( $num % $p == 0 )
return false;
if ($p >= $root)
break;
}
return true;
}
which trashes the array pointer I am iterating on.
I would like to be able to save and restore the array's internal pointer in the IsPrime() function so it doesn't have this side effect. Is there any way to do this?
You can "save" the state of the array:
$state = key($array);
And "restore" (not sure if there's a better method):
reset($array);
while(key($array) != $state)
next($array);
Don't rely on array pointers. Use iterators instead.
You can replace your outer code with:
foreach ($primes as $p) {
if ($p > 10000 && IsPrime(doSomeCalculationsOn($p))) {
return $p;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With