0

我遇到的问题是在 Python 中正确执行 ' chakravala ' 方法。它正常运行直到 n = 181。我尝试将组合方法集成到我的函数中,但几乎立即运行到小数。溢出。

字符串文字是我在集成方面的尝试,其他一切都是从这个循环中运行的函数:

    for n in natural_number_generator(1):
    print(n)
    if n in squares_list:
        continue
    else:
        a = floor(sqrt(n))
        b = 1
        k = a ** 2 - n
        answer_list.append(chakravala(n, a, b, k))
        if answer_list[-1][1] > maximum:
            maximum = answer_list[-1][1]
            answer = answer_list[-1][0]
    # Breaks out of main loop when N reaches limit.
    if n >= limit:
        break

实际功能:

def chakravala(n, a, b, k):
    # Creates variables and prints to check.
    m_list = []
    print(a, b, k)
    minimum = inf

    # Final step of iteration
    if k == 1:
        return [n, a, b]

    #TODO: Fix
    """
    if k in [-1, -2, -4, 2, 4]:
        while True:
            a, b = a ** 2 + n * b ** 2, 2 * a * b
            k = k ** 2
            if k != 1:
                a, b = Decimal(a / sqrt(k)), Decimal(b / sqrt(k))
                k = Decimal(k / k)
            else:
                a, b = Decimal(a / k), Decimal(b / k)
                k = Decimal(k / k)
            print(a, b, k)
            if float(a).is_integer() and float(b).is_integer():
                return [n, a, b]
            else:
                continue"""

    # Fills our m_list.
    for m in natural_number_generator(1):
        if (a + b * m) % abs(k) == 0:
            m_list.append(m)
            if m >= 2 * n:
                break

    # Finds the m for which abs(m^2 - n) is minimized.
    for i, check_m in enumerate(m_list):
        difference = check_m ** 2 - n
        if difference < minimum:
            m = check_m
            minimum = difference
        elif difference > minimum:
            break

    # Creates the next set of variables for iteration.
    a, b = (a * m + n * b) / abs(k), (a + m * b) / abs(k)
    k = (m ** 2 - n) / k
    a, b, k = int(a), int(b), int(k)
    return chakravala(n, a, b, k)

非常感谢任何帮助。

4

1 回答 1

0

在 math.stackexchange.com 上解决了问题!我在 n = 181 时遇到的问题是我使用了浮点变量,它们越过了 2^52 的不可见边界。要“解决”问题,只需在 / 的位置插入几个 //。

代码:

def chakravala(n, a, b, k):
# Creates variables and prints to check.
m_list = []
minimum = inf
m = 0
# Final step of iteration
if k == 1:
    return [n, a, b]

# Fills our m_list.
for m in natural_number_generator(1):
    if (a + b * m) % abs(k) == 0:
        m_list.append(m)
        if m >= 2 * n:
            break

# Finds the m for which abs(m^2 - n) is minimized.
for i, check_m in enumerate(m_list):
    difference = check_m ** 2 - n
    if difference < minimum:
        m = check_m
        minimum = difference
    elif difference > minimum:
        break

# Creates the next set of variables for iteration.
a, b = (a * m + n * b) // abs(k), (a + m * b) // abs(k)
k = (m ** 2 - n) // k
return chakravala(n, a, b, k)

再次感谢您在 math.stackexchange.com 上的 Sil :)

于 2020-09-04T10:58:34.173 回答