问题描述
注意:我在 Python 方面没有那么丰富的经验,因此我的代码可能不如预期的好。
我正在尝试创建一个工具来帮助计算某种形式的数字的代数因子(请参阅 https://en.wikipedia.org/wiki/Aurifeuillean_factorization)。这主要是作为一种测试/学习体验,但是我在尝试计算参数“c”时遇到了问题,该参数定义为 2^(2k+1)+1。添加步骤对我不起作用。我只是将返回值设为 2^129,而不是我希望获得的 2^129+1。这是 Python 本身的问题,还是我在这方面犯了某种错误。
代码:
import math
def make_aurifeuille_factors(base,exponent):
if base == 2 and exponent % 4 == 2:
k = (exponent - 2) / 4
c = int(1 + 2 ** (2*k + 1))
d = int(2 ** (k + 1))
L = c + d
M = c - d
return int(k),int(c),int(d),int(L),int(M)
def gcd(a,b):
return int(math.gcd(a,b))
print(make_aurifeuille_factors(2,258))
解决方法
k = (exponent - 2) / 4
使 k
成为 float
,这意味着您可能会在计算中引入数值错误。使用整数除法从一开始就停留在 int
世界:
def make_aurifeuille_factors(base,exponent):
if base == 2 and exponent % 4 == 2:
k = (exponent - 2) // 4
c = 1 + 2 ** (2*k + 1)
d = 2 ** (k + 1)
L = c + d
M = c - d
return k,c,d,L,M