PHP - check if number is prime

后端 未结 18 1399
野趣味
野趣味 2021-01-25 00:03

I\'m trying to create a function which checks whether the number is prime or not. BUT I want this function to echo to the user \'prime\' or \'NOT prime\' - and that\'s where my

18条回答
  •  闹比i
    闹比i (楼主)
    2021-01-25 00:40

    That is my solution. If you put the condition in the loop and break after it, it's never going to finish with the check.

    $num = rand ( 1, 1000 );
    
    $notPri = null;
    
    for($check = 2; $check < $num; $check ++) {
    
          if ($num % $check == 0) {
              $notPri ++;
             }
           }
    
    if ($neEpri == 0) {
    
        echo $num . "
    Prime!"; } else { echo $num . "
    Not a prime!"; }

提交回复
热议问题