gpt4 book ai didi

Php质因数分解时间和大小问题

转载 作者:行者123 更新时间:2023-11-30 22:42:26 27 4
gpt4 key购买 nike

有一个用于质因数分解python实现代码。返回答案大约需要 0.1 秒。我为 php 实现了它。在大量情况下,它运行大约 3 秒(有时它永远不会返回答案)

注意:我什至使用了 BCMath PHP 中用于处理非常大的数字的函数。

注意:此函数内的所有其他函数(如下所述)均单独测试,但其中一个使用 php 内置函数 gmp_mod< 的函数 (pollard_brent) 存在问题。当我运行这个时:

// python handles these big numbers fine, and returns 1 for this:
echo gmp_mod(10000000000000000000001 , 2);

给我这个错误:

Message: gmp_mod(): Unable to convert variable to GMP - wrong type

我的分解代码:

public function primefactors($n, $sort = false) {
$smallprimes = $this->primesbelow(10000);
$factors = [];

$limit = bcadd((bcpow($n, 0.5)) , 1);

foreach ($smallprimes as $checker) {
if ($checker > $limit) {
break;
}
// while ($n%$checker == 0) {
while ( bcmod($n, $checker) == 0 ) {
array_push($factors, $checker);
// $n = (int)($n/$checker);
$n = bcdiv($n, $checker);
// $limit = (int)(bcpow($n, 0.5)) + 1;
// $limit = (bcpow($n, 0.5)) + 1;
$limit = bcadd((bcpow($n, 0.5)) , 1);
if ($checker > $limit) {
break;
}
}
}

if ($n < 2) {
return $factors;
}

while ($n > 1) {
if ($this->isprime($n)) {
array_push($factors, $n);
// var_dump($factors);
break;
}
$factor = $this->pollard_brent($n);
$factors = array_merge($factors, $this->primefactors($factor));
$n = (int)($n/$factor);
}
if ($sort) {
sort($factors);
}

return $factors;

}

有什么想法吗?

最佳答案

正如注释中所指出的,手册显示两个参数都必须是 GMP 对象或数字字符串。这有效:

echo gmp_mod("10000000000000000000001", "2");

较小的数字可能会起作用,因为 PHP 会在函数内将整数转换为字符串,但是 10000000000000000000001PHP_INT_MAX 长,因此它不起作用。

echo 10000000000000000000001;

产量:

1.0E+22

关于Php质因数分解时间和大小问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42144228/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com