1
我寫的代碼有什麼問題? 即時通訊試圖解決歐拉項目中的一個問題。找到特定號碼的主要因素
謝謝:)
我加引號的代碼可以讓你瞭解我的一切都做了。它適用於13915號碼,但不適用於我需要的號碼。
問題是,即時檢查數字被分爲3,雖然它不是一個完整的數字,但它仍然說它是一個素數。
例如:
3 is a prime factor of 600851475143
new number: 200283825047.67
new largest prime: 3
<?php
/**
* Created by PhpStorm.
* User: gabia_000
* Date: 13/08/2015
* Time: 23:32
*
* Project euler - Question 3 ;
* The prime factors of 13195 are 5, 7, 13 and 29.
* What is the largest prime factor of the number 600851475143 ? ;
*/
$num = 600851475143; // The number that contains the factors ;
$largest = 1; // the largest prime factor ;
$n = 3; // the count of number starting 3 to find the prime factor ;
echo '<b>number - '.$num.'</b><br /><br />'; // DISPLAY ;
while ($num > 1) { // as long as the number isnt 1 yet ;
$prime = 1; // defult true - the $n is prime;
$i = 2; // number that the prime is divide by ;
while($i < $n && $prime == 1) { // as long as $n is bigger then $i and prime is still true ;
if($n % $i == 0) { // if $n is divided in $i ;
$prime = 0; // prime false ;
echo "{$n} not a prime, divided by {$i}.<br />"; // DISPLAY ;
break 1; // break the while ;
}
$i = $i + 1; // increase the $i by 1 ;
}
if ($prime) { // if the prime is still true ;
if($num % $n == 0) { // if the prime number is a factor of the number ;
echo "{$n} is a prime factor of {$num}<br />"; // DISPLAY ;
$num = $num/$n; // set the new number ;
echo " - new number: {$num}<br />"; // DISPLAY ;
$largest = $n; // set the new largest prime factor ;
echo " - new largest prime: {$largest}<br />"; // DISPLAY ;
}
else { // if the prime number isnt a factor of the number ;
echo "{$n} is not a prime factor of {$num}<br />"; // DISPLAY ;
}
}
$n = $n + 1; // increase the $n by 1 ;
if($n > $num) { // if the $n is bigger then the number is there is no prime factor ;
break ; // break the while ;
echo "<br /><br /><b>no prime factors for </b>{$num}}"; // DISPLAY ;
}
}
// DISPLAY END RESULTS ;
echo "
latest \$n - <b>{$n}</b><br />
largest prime - <b>{$largest}</b><br />
number - {$num}
";
im用於涵蓋有關代碼的每個方面。無論如何這是行不通的,得到了一個致命錯誤: (!)致命錯誤:最大執行時間超過120秒C:\ wamp \ www \ project_euler \ prime.php在第29行 – GabiArzu
@GabiArzu我編輯了代碼。你只需要從'$ n = 2'開始 –
仍然是一樣的錯誤... – GabiArzu