今天年前最后一天上班,心思比较乱,为了熟悉php,所以使用php做一下Project Euler的题,果然让我遇到了一些费解的部分,比如这题:
The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ?
这题翻译成中文是:
13195的因子有5、7、13和29。什么是600851475143的最大质数因子?
为了测试是否溢出,开始的时候直接写了
echo 600851475143+1;
发现结果正常,以为不会溢出,所以最初的解题是这样写的:
public function getResult()
$max = 0;
$num = 600851475143;
for ($index = 2; $index <= sqrt($num); $index++) {
while($num%$index == 0){
$max = $index;
$num = $num / $index;
}
}
return $max>$num?$max:$num;
}
结果郁闷的发现,结果竟然是小数:2023068939.8754;
于是我写成这样:
public function getResult()
$max = 0;
$num = 600851475143;
for ($index = 2; $index <= sqrt($num); $index++) {
while (strpos($num/$index,'.')===FALSE) {
$max = $index;
$num = $num / $index;
}
}
return $max>$num?$max:$num;
}
这样正常,然后很郁闷,你丫的600851475143不溢出,600851475143%xx溢出了?
后面知道大整数(600851475143类型为float)取余会强制转换为int,然后就溢出了。。。
百度找到一个解决方案:intval(fmod(floatval(bn), b n ) , sn))
不过感觉还是我这个比较好?strpos(num/ n u m / index,’.’)===FALSE