PHP - check if number is prime

后端 未结 18 1394
野趣味
野趣味 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条回答
  •  生来不讨喜
    2021-01-25 00:45

    $num = ceil(sqrt($num));
    
    $is_prime = true;
    for($j=3; $j<=$num; $j=$j+2){
        if($i%$j == 0){         
            $is_prime = false;
            break;
        }
    }
    
    if($is_prime){
        echo "No is Prime";
    }
    

    Note: Start loop from 2 as it is the only even prime no. Increment with 2 as no even no is a prime no.

    => Code for finding all prime no in range (2-100)

    $limit = 100; $arr = array(2);
    for($i=3; $i<=$limit; $i=$i+2){
    
        $num = ceil(sqrt($i));
    
        $is_prime = true;
        for($j=3; $j<=$num; $j=$j+2){
            if($i%$j == 0){         
                $is_prime = false;
                break;
            }
        }
    
        if($is_prime){
            $arr[] = $i;
        }
    }
    

提交回复
热议问题