费马自动支票

2024-09-27 07:29:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个脚本,它将自动循环通过一组数字,并对照Fermat反例检查它们。我已经有了一个脚本,它从用户那里获取数字输入,并对照反例检查它们。我想做的是使这个系统自动化,并在特定范围内获取数字检查反例an+bn=c**n中这些数字的所有可能组合,其中n>;2。我想画出这个方程,然后让它在那个图上运行。如果你对如何做到这一点有任何其他想法,请帮助。我已经检查了一些其他来源,但不能得到一个真正的掌握如何得到一个图形到代码中。你知道吗

def prompt_yesno(prompt):
   return input(prompt) in 'Yy'

def prompt_int(prompt, min=None):
    while True:
        try:
            ans = int(input(prompt))
            if min is None or min <= ans:
                return ans
        except ValueError:
            print("Input must be an integer.")

def is_fermat_counterexample(a, b, c, n):
    return n > 2 and a**n + b**n == c**n

def fermat_demo():
    print("Let's see if Fermat was right.")
    print("He claims that a^n + b^n = c^n cannot be true for any n > 2.")
    a = prompt_int('Give a positive integer for "a": ', 1)
    b = prompt_int('Give a positive integer for "b": ', 1)
    c = prompt_int('Give a positive integer for "c": ', 1)
    n = prompt_int('Give an integer bigger than 2 for exponent "n": ', 3)
    print("Fermat was incorrect"
      if is_fermat_counterexample(a, b, c, n) else
      "No, that does not work!")

while True:
    fermat_demo()
    if not prompt_yesno("Would you like to try again?\n"
                    "Type 'Y' to continue and 'N' to exit: "):
        break

Tags: anforreturnifdef数字integermin
1条回答
网友
1楼 · 发布于 2024-09-27 07:29:32

最好只取a、b和n的范围,然后计算c。 如果a,b的范围是[1到X],n的范围是[3到n],则对(a,b,n)的每个组合调用以下方法以找到反例-

def is_fermat_counterexample(a, b, n):
    value = a**n + b**n
    c = value**(1/n)
    return (c.is_integer() and (int(c) > 0))

相关问题 更多 >

    热门问题