douwei1950 2015-04-27 18:53 采纳率: 0%
浏览 77
已采纳

检测输入是否是PHP中的素数 - 关注最佳实践代码语法[重复]

This question already has an answer here:

I'm teaching my wife to code, so we made a simple prime-number detector.

We came up with this, but I'm wondering if there's a better / neater way. I particularly don't like the 0/1 switch for displaying the end statement.

//get n from URL
$n = $_GET['n'];

$j=2;
$prime=1;

while ($j<=($n/2)){

    if (is_int($n/$j)){ $prime=0;
        break;
    }

   $j++;

}

if ($prime==1) {echo "Yes! $n is a prime number";}
else {echo "No, $n is not a prime number";}
</div>
  • 写回答

2条回答 默认 最新

  • duandao7704 2015-04-27 20:04
    关注

    There is always the neat and newbie friendly regular expressions way of finding prime numbers:

    $n = $_GET['n'];
    echo "$n is ", preg_match('/^1?$|^(11+?)\1+$/', str_repeat('1', $n))
        ? "not " : "", "a prime number", PHP_EOL;
    

    No seriously, what I would suggest is that you tidy up your code a bit, so it gets easier to read:

    • Remove unnecessary parentheses
    • Rename $prime to $isPrime
    • Change $j++ into $j = $j + 1
    • Add a quick check on 0, 1 which are not prime numbers

    Like so:

    // Get parameter 'n' from URL
    $n = $_GET['n'];
    
    if ($n <= 1) {
        $isPrime = false;
    }
    else {
        $isPrime = true;
        $j = 2;
    
        while ($j <= $n / 2) {
            if (is_int($n / $j)) {
                $isPrime = false;
                break;
            }
            $j = $j + 1;
        }
    }
    
    if ($isPrime) {
        echo "$n is a prime number";
    }
    else {
        echo "$n is not a prime number";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器