PHP - 检查数字是否为素数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38008130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP - check if number is prime
提问by Piter
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 problem starts. Let me show you my code:
我正在尝试创建一个函数来检查数字是否为素数。但我希望这个函数能够向用户发出“prime”或“not prime”的回应——这就是我的问题开始的地方。让我向您展示我的代码:
class IsPrime
{
function check($num)
{
for ($i = 2; $i < $num; $i++)
{
if ($num % $i == 0)
{
echo 'NOT prime';
break;
}
}
echo 'Prime';
}
}
$x = new IsPrime();
$x->check(4);
The problem is that when I put any prime number - it works correctly, but when I put any not prime number - it also echos second echo, sth like this: 'NOT prime prime'
.
问题是,当我把所有的素数-它工作正常,但是当我把任何不素数-也回声第二回声,某事像这样:'NOT prime prime'
。
How can I make it echo only the right answer ?
我怎样才能让它只回应正确的答案?
回答by Titus
in 5459 bytes:
在5459 个字节中:
function is_prime($n){for($i=$n;--$i&&$n%$i;);return$i==1;}
loops $i
down from $n-1
until it finds a divisor of $n
; $n
is prime if that divisor is 1.
$i
向下循环,$n-1
直到找到 的除数$n
;$n
如果该除数为 1,则为素数。
add 10 bytes for much better performance:
添加 10 个字节以获得更好的性能:
function is_prime($n){for($i=$n**.5|1;$i&&$n%$i--;);return!$i&&$n>1;}
loops $i
from (approx.) sqrt($n)
to 1
looking for a divisor with a post-decrement on $i.
If the divisor is 1
, $i
will be 0
at the end, and !$i
gives true
.
$i
从(大约)循环sqrt($n)
到1
寻找一个在 $i 上有后递减的除数。
如果除数是1
,$i
将0
在最后,并!$i
给出true
。
This solition uses a trick: For $n=2
or 3
, $i
will be initialized to 1 → loop exits in first iteration. For larger even square roots ($n**.5|0
), |1
serves as +1
. For odd square roots, +1
is not needed because: if $n
is divisible by root+1
, it is also divisible by 2
. Unfortunately, this can cost a lot of iterations; so you better
这个孤立使用一个技巧: For $n=2
or 3
,$i
将在第一次迭代中初始化为 1 → 循环退出。对于较大的偶数平方根 ( $n**.5|0
),|1
用作+1
。对于奇数平方根,+1
不需要,因为:如果可以$n
被 整除root+1
,也可以被 整除2
。不幸的是,这会花费大量的迭代;所以你更好
add another 7 bytes for even better performance:
添加另外 7 个字节以获得更好的性能:
function is_prime($n){for($i=~-$n**.5|0;$i&&$n%$i--;);return!$i&$n>2|$n==2;}
$n=2
needs a special case here: inital $i=2
divides $n=2
→ final $i=1
→ returns false
.
$n=2
这里需要一个特殊情况:inital$i=2
分歧$n=2
→最终$i=1
→回报false
。
Adding 1
to $n
instead of the square root is enough to avoid failures; but:
添加1
到$n
而不是平方根就足以避免失败;但:
I did not count the iterations but only tested time consumption; and that only in TiO instead of a controlled environment. The difference between the last two versions was smaller than the deviation between several runs. Significant test results may be added later.
我没有计算迭代次数,只测试了时间消耗;并且仅在 TiO 中而不是在受控环境中。最后两个版本之间的差异小于几次运行之间的偏差。稍后可能会添加重要的测试结果。
回答by Vijay Srinivas
This could be a long procedure if the number is really a prime number. There is a shorter procedure as well. We need not run the for loop upto the number itself. Instead, we can run it upto the Highest Integer less than or equal to the square root of the number.
如果该数字确实是质数,这可能是一个很长的过程。还有一个更短的程序。我们不需要将 for 循环运行到数字本身。相反,我们可以将它运行到小于或等于数字平方根的最高整数。
class IsPrime
{
function check($num)
{
$bCheck = True;
$highestIntegralSquareRoot = floor(sqrt($num));
for ($i = 2; $i <= $highestIntegralSquareRoot; $i++)
{
if ($num % $i == 0)
{
$bCheck = False;
break;
}
}
if $bCheck
echo 'Prime';
else
echo 'NOT prime';
}
}
$x = new IsPrime();
$x->check(97);
Now, in the above, if we check check whether 97 is prime or not (actually, it is), then the loop need not run from 2 to 97, but only from 2 to 9. (Square root of 97 is 9.8488578018, and highest integer less than or equal to that is 9. Similarly, we can check for number 121 (this is not a prime number, as it is divisible by 11). The limit will be increased from 2 to 11 in a similar matter. And so on. Actually, we need to check the divisibility of the number by the smaller prime numbers in the vicinity, but that would be more complex. Hope this helps.
现在,在上面,如果我们检查 97 是否是质数(实际上是),那么循环不需要从 2 运行到 97,而只需从 2 运行到 9。(97 的平方根是 9.8488578018,并且小于或等于 9 的最大整数。同样,我们可以检查数字 121(这不是质数,因为它可以被 11 整除)。在类似的情况下,限制将从 2 增加到 11。并且依此类推。实际上,我们需要检查数字与附近较小素数的整除性,但这会更复杂。希望这会有所帮助。
回答by Said Sabir
You can check number is prime or not & without using loop with this function:
您可以在不使用此函数的循环的情况下检查数字是否为素数:
function is_prime($p) {
$r1 = $p%2;
$r2 = $p%3;
$r3 = $p%5;
return ($p > 1) && (($r1 >= 1) && ($r2 >= 1) && ($r3 >= 1)) || in_array($p, [2,3,5]);
}
回答by GAVD
As many answer pointed out, your logic code has a problem: when you get i
such that num % i == 0
, you print "NOT prime" and quit the loop, after that, you still print "Prime". Some guys moved echo "Prime"
in if-else
, it is still wrong. One way to approach, for example,
正如许多答案指出的那样,您的逻辑代码有一个问题:当您得到i
这样的 that 时num % i == 0
,您打印“NOT prime”并退出循环,之后,您仍然打印“Prime”。有些人搬进来echo "Prime"
了if-else
,还是错的。一种方法,例如,
class IsPrime
{
function check($num)
{
$bCheck = True;
for ($i = 2; $i < $num; $i++)
{
if ($num % $i == 0)
{
$bCheck = False;
break;
}
}
if $bCheck
echo 'Prime';
else
echo 'NOT prime';
}
}
$x = new IsPrime();
$x->check(4);
回答by Hajis Hakkim
You can find prime numbers and non prime numbers from 1 to your limit and its count.
您可以找到从 1 到您的极限及其计数的素数和非素数。
public function prime_checker($count){
$counter=0;
$no_prime=0;
for($i=2 ; $i<=$count; $i++ ){
for($j=2 ; $j<$i ; $j++ ){
if($i % $j == 0){
echo $i.'is not prime<br/>';
$no_prime=$i;
break;
}
}
if($i != $no_prime){
$prime_numbers[$counter]=$i;
$counter=$counter+1;
}
}
echo '<br/>'.$counter.'prime numbers<br/><br/>';
for($i=0 ; $i<$counter ; $i++ ){
echo $prime_numbers[$i].' is prime<br/>';
}
}
回答by Fefar Ravi
<?php
function primeCheck($num)
{
if ($num == 1)
return false;
for ($i = 2; $i <= $num/2; $i++)
{
if ($num % $i == 0)
{
return false;
}
}
return true;
}
$primeNumber = primeCheck(17);
if ($primeNumber == true)
{
echo "Is Prime";
}
else
{
echo "Is Not Prime";
}
?>
回答by P bertJoha
The break is only breaking the for loop,
use return;
instead. it will exit the function
break 只是中断 for 循环,return;
而是使用。它将退出该功能
回答by ixe
Justuse return:
只需使用返回:
class IsPrime
{
function check($num)
{
for ($i = 2; $i < $num; $i++)
{
if ($num % $i == 0)
{
echo 'NOT prime';
return; // that you need
}
}
echo 'Prime';
}
}
$x = new IsPrime();
$x->check(4);
回答by Manish Jesani
Please Check this
请检查这个
class IsPrime
{
function check($num)
{
for ($i = 2; $i < $num; $i++)
{
if ($num % $i == 0)
{
return 'NOT prime';
}
}
return 'Prime';
}
}
$x = new IsPrime();
$result = $x->check(4);
echo $result;
回答by Shibon
try this
尝试这个
class IsPrime
{
function check($num)
{
for ($i = 2; $i < $num; $i++)
{
if ($num % $i == 0)
{
echo 'NOT prime';
break;
}
else
{
echo 'Prime';
}
}
//echo 'Prime';
}
}
$x = new IsPrime();
$x->check(3);