我有一個關聯數組,即如何存儲和重置PHP數組指針?
$primes = array(
2=>2,
3=>3,
5=>5,
7=>7,
11=>11,
13=>13,
17=>17,
// ...etc
);
然後我做
// 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;
}
的問題是,IsPrime也遍歷$素數數組,
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;
}
它象垃圾一樣清除數組我正在迭代的指針。
我想能夠保存和恢復數組的內部指針在IsPrime()函數,所以它沒有這種副作用。有沒有辦法做到這一點?
+1爲危險,威爾羅賓遜! – n0nag0n 2012-08-22 20:39:52