verry faster

This commit is contained in:
gnieark 2015-11-15 22:53:49 +01:00
parent 6f995bb87d
commit 513f500b22
2 changed files with 55 additions and 31 deletions

42
_functions.php Normal file
View File

@ -0,0 +1,42 @@
<?php
function isPrimary($number){
$i=1;
while(getPrimeNumber($i) <= sqrt($number)){
if(fmod($i,getPrimeNumber($i))==0){
return false;
}
$i=$i+2;
}
return true;
}
function getPrimeNumber($order){
static $primeNumbersList=array(2,3);
//if already finded:
if(isset($primeNumbersList[$order-1])){
return $primeNumbersList[$order-1];
}
$i=$primeNumbersList[count($primeNumbersList)-1] + 2;
while (count($primeNumbersList) < $order){
$isPrimaryNumber=true;
foreach($primeNumbersList as $pr){
if($pr>sqrt($i)){
break;
}
if(fmod($i,$pr)==0){
$isPrimaryNumber=false;
break;
}
}
if($isPrimaryNumber){
$primeNumbersList[]=$i;
}
$i=$i+2;//sert à rien de tester les nombres pairs
}
return $i-2;
}

View File

@ -3,37 +3,19 @@
* Gnieark's anwser to euler problem 3 * Gnieark's anwser to euler problem 3
* https://projecteuler.net/problem=3 * https://projecteuler.net/problem=3
*/ */
require_once("_functions.php");
echo largestPrimeFactorOf(600851475143); echo largestPrimeFactorOf(600851475143);
function largestPrimeFactorOf($number){ function largestPrimeFactorOf($number){
$primesNumbers=array(2);//non considering value 1 $right=$number;
$i=3; //begin to 3 $i=1;
$prFact=1;
while($i<=sqrt($number)){ while(getPrimeNumber($i)<=$right){
//echo $i; if(fmod($right,getPrimeNumber($i))==0){
//is $i a factorOf $number $prFact=getPrimeNumber($i);
if(fmod($number,$i)==0){ $right=$right/$prFact;
//is $i a prime number }
$index=0; $i++;
$isPr=true;
while(($primesNumbers[$index]<sqrt($i)) && $index < (count($primesNumbers))-1){
if((fmod($i,$primesNumbers[$index])==0)){
$isPr=false;
break;
}
$index++;
}
if($isPr){
$primesNumbers[]=$i;
$lastPr=$i;
}
}
$i=$i+2;
} }
if (isset($lastPr)){ return $prFact;
return $lastPr; }
}else{
return 1;
}
}