猿问

在循环中查找素数的公式

我需要使用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;

}

?>

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


胡说叔叔
浏览 596回答 3
3回答

炎炎设计

这是我找到一段时间检查底漆的单线纸。它使用计数标记(一元数学)确定:function is_prime_via_preg_expanded($number) {&nbsp; &nbsp; return !preg_match('/^1?$|^(11+?)\1+$/x', str_repeat('1', $number));}依次检查所有数字是否有素数:$i=2; // start here (2 is the first prime)while (1) { // neverending loop&nbsp; &nbsp; if (is_prime_via_preg_expanded($i)) echo $i." <br />\n";&nbsp; &nbsp; $i++;}要仅检查数字范围内的质数,如提供的示例中所示:$start = 2; // start here (2 is the first prime)$end = 100;$i=$start;while ($i<=$end) {&nbsp; &nbsp; if (is_prime_via_preg_expanded($i)) echo $i." <br />\n";&nbsp; &nbsp; $i++;}

饮歌长啸

这是一个基本的实现:function prima($n){&nbsp; for($i=1;$i<=$n;$i++){&nbsp; //numbers to be checked as prime&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $counter = 0;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for($j=1;$j<=$i;$j++){ //all divisible factors&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if($i % $j==0){&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $counter++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; //prime requires 2 rules ( divisible by 1 and divisible by itself)&nbsp; &nbsp; &nbsp; &nbsp; if($counter==2){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;print $i." is Prime <br/>";&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}&nbsp;prima(20);&nbsp; //find prime numbers from 1-20这将输出&nbsp;2 is Prime&nbsp;&nbsp;3 is Prime&nbsp;&nbsp;5 is Prime&nbsp;&nbsp;7 is Prime&nbsp;&nbsp;11 is Prime&nbsp;&nbsp;13 is Prime&nbsp;&nbsp;17 is Prime&nbsp;&nbsp;19 is Prime&nbsp;
随时随地看视频慕课网APP
我要回答