I would like to make a program which can calculate first 5000 primary numbers whos ends with 9 :
I tried this but it didn't work :
$div9 = [];
$x = 2;
while (count($div9) <= 5000) {
function findPrime($x)
{
for ($i = 2; $i < ($x / 2); $i ) {
$rest = $x % $i;
if ($rest == 0) {
break;
}
}
return $x;
}
$primeList[] = $x;
for ($j = 0; $j < count($primeList); $j ) {
$array = array_map('intval', str_split($primeList[$j]));
if (end($array[$j]) === 9) {
return $primeList[$j];
$div9[] = $primeList[$j];
}
}
$x ;
}
any hints please?
CodePudding user response:
You should not define a function inside your while loop
This should help
function check_prime($num)
{
if ($num == 1)
return false;
for ($i = 2; $i <= $num/2; $i )
{
if ($num % $i == 0)
return false;
}
return true;
}
$div9 = [];
$i = 0;
while(count($div9) < 5000) {
if($i === 9 && check_prime($i)) {
$div9[] = $i;
}
$i ;
}
CodePudding user response:
Another variation on the theme, the isPrime
function was ported from Javascript cryptoJS library.
# Adapted from CryptoJS v3.1.2
function isPrime( $n=0 ){
$r=sqrt( $n );
for( $f=2; $f <= $r; $f ){
if( !( $n % $f ) )return false;
}
return true;
}
function isFactor($n,$f){
return $n % 10 == $f;
}
$limit=5000;
$primes=[];
$x=2;
$f=9;
while( count( $primes ) < $limit ){
if( isPrime( $x ) && isFactor( $x, $f ) )$primes[]=$x;
$x ;
}
printf('<pre>%s</pre>',print_r($primes,true));