我需要帮助才能使此测试尽可能高效。用户输入一个数字,我测试所有数字,直到用户编号。
function primetest($pt) {
$prime_numbers = file("prime.txt", FILE_IGNORE_NEW_LINES);
$max = sizeof($prime_numbers);
for ($i = 0; $i < $max; $i++) {
if ($prime_numbers[$i] < $pt) {
if ($pt % $prime_numbers[$i] == 0) {
$i = $max;
return false;
}
} else {
$i = $max;
}
}
return true;
}
$userinput_number = $_POST['f_userinput_number'];
if (isset($userinput_number) == false) {
echo '<form action="20160505.php" method=POST>
<strong>Number range to test for prime.</strong>
'.last_num().'-
<input type="text" name="f_userinput_number">
<input type="submit" value="Submit">
</form>';
} else {
#WORKS
$last_num_test = last_num();
if (($userinput_number > 1) && ($userinput_number == (intval($userinput_number))) && ($last_num_test <= $userinput_number)) {
for ($i = last_num(); $i < $userinput_number; $i= $i + 2) {
$test = primetest($i);
if ($test == false) {
echo "<b><font color=\"red\">X</font> $i is not prime</b>";
} else {
#To append number if not already in array and inform user if number is prime.
save($i);
}
}
} else {
echo "Make sure the number is a <b>natural number</b>, and is greater than or equal to <b> ".last_num()."</b>";
}
}
答案 0 :(得分:1)
这正是你要找的......
<?php
//Prime Function
function fn_prime($number) {
$i = 2; $result = TRUE;
while($i < $number) {
if(!($number%$i)) {
$result = FALSE;
}
$i++;
}
return $result;
}
?>
答案 1 :(得分:0)
Here是确定数字是否为素数的好函数:
function isPrime($num) {
if($num == 1)
return false;
if($num == 2)
return true;
if($num % 2 == 0) {
return false;
}
for($i = 3; $i <= ceil(sqrt($num)); $i = $i + 2) {
if($num % $i == 0)
return false;
}
return true;
}