Python经典练习题1:一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?

Python经典练习题

网上能够搜得到的答案为:

for i in range(1,85):
    if 168 % i == 0:
        j = 168 / i;
        if  i > j and (i + j) % 2 == 0 and (i - j) % 2 == 0 :
            m = (i + j) / 2
            n = (i - j) / 2
            x = n * n - 100
            print(x)

输出答案为:

-99
21
261
1581

但其实四个数字,均不符合+100和+168后,仍为完全平方数的条件;

正确代码如下:

import math
n = 0
count = 0
while True:
    first = n + 100
    second = n + 168
    first_sqrt = int(math.sqrt(first))
    second_sqrt = int(math.sqrt(second))
    if (first_sqrt*first_sqrt == first) and (second_sqrt*second_sqrt == second):
        print(n)
        break
    n = n + 1

正确答案只有一个:

156
原文地址:https://www.cnblogs.com/huxianhe0/p/9276850.html