一尘不染

在循环中查找素数的公式

php

我需要使用for循环或while循环查找素数

我写了这个,但这是错误的

<?php
$i = 1;
while($i<5)
{
    for($j=1; $j<=$i; $j++)
    {
        if ($j != 1 && $j != $i)
        {
            echo $i . "/" . $j . "=" . $i%$j . "<br />";
            if ($i%$j != 0)
            {
                echo $i . "<br />";
            }
        }
    }
    echo "<br />";
    $i += 1;
}
?>

有没有一种方法可以将数字与数组相除以找到余数?


阅读 252

收藏
2020-05-26

共1个答案

一尘不染

这是我发现的一个小功能:(http://icdif.com/computing/2011/09/15/check-number-prime-
number/)似乎对我有用!

function isPrime($num) {
    //1 is not prime. See: http://en.wikipedia.org/wiki/Prime_number#Primality_of_one
    if($num == 1)
        return false;

    //2 is prime (the only even number that is prime)
    if($num == 2)
        return true;

    /**
     * if the number is divisible by two, then it's not prime and it's no longer
     * needed to check other even numbers
     */
    if($num % 2 == 0) {
        return false;
    }

    /**
     * Checks the odd numbers. If any of them is a factor, then it returns false.
     * The sqrt can be an aproximation, hence just for the sake of
     * security, one rounds it to the next highest integer value.
     */
    $ceil = ceil(sqrt($num));
    for($i = 3; $i <= $ceil; $i = $i + 2) {
        if($num % $i == 0)
            return false;
    }

    return true;
}
2020-05-26