猿问

Python-是数字 pronic,如果没有找到最近的 pronic 数字

任务是让一些输入数字找出那个数字 pronic,如果没有找到最接近输入数字的 pronic 数字。问题是如何编写其余的代码。我设法完成了第一部分,并找出输入的数字是否是 pronic。问题是如果输入的数字不是 pronic,我找不到找到最近的较大数字的好方法。我有一个想法添加到嵌套 for 循环的 else 部分中,以查找从 1 到 n 的所有 pronic 数字,将它们附加到列表中并找到该列表的最大值,但即使我这样做,我也只会找到最接近的较小数字,而不是最接近的也可能大于给定的数字。目前,我有:


flag=0

n=int(input('Enter the number: '))

for i in range(1,n):

    if i*(i+1)==n:

        flag=1

if flag==1:

    print('Entered number is pronic!')

else:

    def pro(n):

        flag=False

        for j in range(1,n):

            if j*(j+1)==n:

                flag=True

                break

        return flag

list1=[]

for i in range(1,n):

    if pro(i):

        list1.append(i)

print('Not pronic. Closest smaller pronic number: ',max(list1))


慕娘9325324
浏览 117回答 1
1回答

料青山看我应如是

当试图用代码解决问题时,你最好重用其他人编写的代码来解决类似的问题。一开始发现“相似”的问题可能很困难,但通过练习很快就会变得更容易!在这种情况下,我将利用“pronic numbers”被定义为“两个连续整数的乘积”这一事实。使用你的变量名,我们可以把它变成优化问题:找到i最接近i*(i+1)的整数n。我首先注意到它i*(i+1)看起来很像i*i,这是通过取平方根来反转的。计算机可以很容易地求平方根,所以这sqrt(n)将是寻找平方根的一个很好的起点i用几个数字试试这个:&nbsp;n sqrt(n) nearest&nbsp; i&nbsp;6&nbsp; &nbsp;~2.4&nbsp; &nbsp; &nbsp;6&nbsp; &nbsp; &nbsp;2&nbsp;7&nbsp; &nbsp;~2.6&nbsp; &nbsp; &nbsp;6&nbsp; &nbsp; &nbsp;2&nbsp;8&nbsp; &nbsp;~2.8&nbsp; &nbsp; &nbsp;6&nbsp; &nbsp; &nbsp;2&nbsp;9&nbsp; &nbsp; 3.0&nbsp; &nbsp; 12&nbsp; &nbsp; &nbsp;311&nbsp; &nbsp;~3.3&nbsp; &nbsp; 12&nbsp; &nbsp; &nbsp;312&nbsp; &nbsp;~3.5&nbsp; &nbsp; 12&nbsp; &nbsp; &nbsp;3我们可以看到,小数部分sqrt(n)也为我们提供了有关“最近”普罗尼克数的信息:<0.5 表示我们需要一个较小的数字,>0.5 表示我们需要一个较大的数字,这类似于“四舍五入”一个数字。我们还可以看到,i用来获取最近数的只是整数部分sqrt转移到 Python 代码,我们可以这样做:from math import sqrtdef nearest_pronic(n):&nbsp; i = int(sqrt(n))&nbsp; return i * (i+1)您可以随意使用它,例如:n = float(input('give me a number'))np = nearest_pronic(n)if n == np:&nbsp; print(f"{n} is a pronic number")else:&nbsp; print(f"the nearest pronic number to {n} is {np}")这对我来说是正确的。
随时随地看视频慕课网APP

相关分类

Python
我要回答