模数PHP问题 [英] Modulus PHP Problem
问题描述
我有一个问题,我试图计算一个数字的最低质数是什么,但是我不明白PHP给我的结果.
I have a problem, I am trying to calculate what the lowest prime is of a number but I do not understand the result that PHP is giving me.
如果我有这个电话号码
$number = 600851475143;
然后我将其模量:
$primes = array( 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97);
foreach($primes as $key=>$value) {
if($number % $value == 0 ) {echo $value; break; }
}
为什么$ value = 3?如果$ value = 3,则表示600851475143/3 应该是整数,但不是.所以我不明白为什么if()的计算结果为true?
Why is it that $value = 3? If $value = 3, that means that 600851475143 / 3 should be an integer, but its not. So I do not understand why that if() evaluates to true?
推荐答案
使用PHP 5.2.8,它会按照问题中的说明失败.似乎模运算符不适用于大整数.您应该考虑使用bc_mod
(任意精度的模数):
Using PHP 5.2.8, it fails as described in the question. It seems like the modulo operator doesn't work on big integers. You should consider using bc_mod
(modulus with arbitrary precision):
<?php
$number = 600851475143;
$primes = array(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97);
foreach($primes as $key=>$value)
{
if($number % $value == 0 ) {echo $value."<br/>"; }
if(bcmod($number, $value) == 0) {echo "bcmod ".$value."<br/>"; }
}
?>
上面的代码打印:
3
29
bcmod 71
这篇关于模数PHP问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!