Find the highest prime number in a given range

后端 未结 4 491
不知归路
不知归路 2021-01-26 13:52

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.

<         


        
4条回答
  •  北海茫月
    2021-01-26 14:52

    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...

    =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;
                }
            }
        }
    ?>
    

提交回复
热议问题