问题
I need to find the highest prime number in a given range.
Here is my code which works for 0-100 but if I give 0-125 it is showing prime number as 125.
<?php
$flag=0;
$b=125;
for($i=$b;$i>=0;$i--)
{
if($i%2!=0)
{
for($b=3;$b<10;$b++)
{
if($flag==0)
{
echo('<br>');
if($i%$b!=0)
{
echo('highest prime number is'.$i);
$flag=1;
break;
}
elseif ($i%$b==0)
{
break;
}
}
}
}
}
?>
In the above code I have taken the range from 0-125
回答1:
Yup the problem is algorithmic...
1) You'll need to check up till sqrt($b)
i.e. 11 in this case
2) The $flag
logic is kinda messed up, no use changing the flag then breaking out right after...
<?php
$flag=0;
$b=125;
$sq=sqrt($b);
for($i=$b;$i>=0;$i--)
{
if($i%2!=0)
{
for($b=3;$b<=$sq;$b++)
{
if($i%$b!=0)
{
$flag=1;
}
elseif($i%$b==0)
{
$flag=0;
break;
}
}
if($flag==1){
echo('highest prime number is '.$i);
break;
}
}
}
?>
回答2:
gmp_nextprime()
<?php
$start = 125;
$stop = 0;
for($x=$start;$x>=$stop;$x--){
if(($prime = gmp_intval(gmp_nextprime($x)))<$start){
echo 'The highest prime is '.$prime;
break;
}
}?>
回答3:
thanks for your reply Samuel Cook ..but i need without using 'gmp_nextprime()' function.. iamgetting message 'Call to undefined function gmp_intval() in C:\wamp\www\highprime.php on line 5' – user1659450 16 mins ago
Since you are having difficultly getting gmp functions
to work then you can use
Example 1 : None GMP Function
$range = range(125, 0); // create the range
foreach ( $range as $v ) {
if (isPrime($v)) {
printf('highest prime number is %d', $v);
break;
}
}
If you are able to get gmp working then you can use gmp_prob_prime
Function Used
Example 1 : Using gmp function
foreach ( $range as $v ) {
if (gmp_prob_prime($v) == 2) {
printf('highest prime number is %d', $v);
break;
}
}
Output
highest prime number is 113
Functions Used
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;
}
回答4:
The simplest method you can use is dividing a number starting from 3 with an Array filled by a 2, if modulus (%) gives you an an answer else than 0, it's prime. Then after you got a working code think what can I make better ?
- You could say I want to ignore even numbers! so why iterate over than at all ? just use i = i + 2 (and start by using 3 as seed prime)
- I divide through too many numbers! do you really need to check 21%11, 21%13, 21%17, 21%19 ? They are always smaller than 2 so lets ignore primes > half of it
- Optimize more ? how would limit using a root as maximum in your code affect it ? and Why ?
- Even more ? why couldn't I eliminate all non-primes beforehand and check what's left ?
Try to apply these on your code, or just google a working version.
来源:https://stackoverflow.com/questions/14037688/find-the-highest-prime-number-in-a-given-range