搜索两个整数 root**pwr = integer(user's input)

Con*_*mpt 3 python

我找到的一本书中的一个问题。

编写一个程序,要求用户输入一个整数并打印两个整数,root 和 pwr,这样 0 < pwr < 6 并且 root**pwr 等于用户输入的整数。如果不存在这样的对,打印不可能找到这样的对。

integer = 3 #there will be raw_input but I use it as an example
root = 0

for pwr in range(1,6):

    if root**pwr != integer:
        pwr += 1
        print pwr

    else:
        print root, pwr

    if pwr > 5:     
        pwr = 1
        root += 1
Run Code Online (Sandbox Code Playgroud)

我还没有完成程序,因为我无法正确循环。问题是我收到输出 2、3、4、5、6,然后循环终止。但是,我确实在您看到的最后一个 if 语句代码块中对 pwr 变量使用了重启。但是,它无论如何都会停止执行。这里有什么问题?

小智 5

正如其他人所指出的,这是John Guttag编写的使用 Python的计算和编程简介的第 3.1 节(关于详尽列举)的手指练习,这是大规模开放在线课程MITx的教科书:6.00.1x 计算机科学简介和使用 Python 编程。教科书和课程使用Python 2.7。

我还没有足够高的声誉来评论其他答案,所以请允许我在我的答案开头说,在我发布此内容时,就我所见,之前发布的所有答案都不正确或不完整. 其他答案中的一个常见错误是他们没有考虑所有整数。正确的程序应该解决所有整数的问题,包括正整数和负整数和零(零也是整数)。

在 Guttag 书中的这个练习之前,我们已经介绍了while循环,但没有介绍for循环和range函数,这两者都将在下一节介绍。这是我的答案,仅使用在此练习之前本书中介绍的概念:

num = int(raw_input("Enter an integer: "))
pwr = 1
root = 0
found = False
if num < 0:
    neg = True
else:
    neg = False
while pwr < 6:
    while abs(root**pwr) <= abs(num):
        if root**pwr == num:
            print(str(root) + "**" + str(pwr) + " = " + str(num))
            found = True
        if abs(root) > abs(num):
            root = 0
        elif neg:
            root -= 1
        else:
            root +=1
    pwr += 1
    root = 0
if not found:
    print("No pair of integers, 'root' and 'pwr', exists such that 0 < pwr < 6 and root**pwr = " + str(num))
Run Code Online (Sandbox Code Playgroud)

我已经用整数 0、1、-1、2、-2、8、-8 和其他一些整数测试了这段代码,它似乎有效。