【问题标题】:My programs works but i don't know whether my source code is idle or not我的程序可以运行,但我不知道我的源代码是否空闲
【发布时间】:2021-05-15 21:53:13
【问题描述】:

我在网上学习python,我写了这段代码来判断一个数字是否是素数。问题是他们所做的与我在代码中编写的非常不同,所以我能得到任何关于如何使我的代码更高效或更好的建议吗?此外,这不是我制作的唯一程序,我正在练习许多程序,其中许多程序有效,但我怀疑我的方法是否正确以及我的编码效率低下

n = int(input("Enter the number "))
c = 2
r= n%c
while(r>0):
    c = c+1
    r = n%c
if (c==n):
    print("The number is prime number");
else:
    print("The number you entered is not a prime number")
    print("it is divisible by ",c)

【问题讨论】:

  • 请记住始终用您使用的语言标记您的问题——在这种情况下为python。语言标签是提问时最重要的标签;没有它,问题就更难找到(对于那些回答和未来的观众)。

标签: if-statement input while-loop printing integer


【解决方案1】:

您只能检查 n/2 的 n 插入

【讨论】:

    【解决方案2】:

    如果您是 python 新手,那么您的代码就可以了。 更简洁的代码请参考以下代码:

    n = int(input("Enter the number "))
    c = 2
    while(n%c>0):
        c = c+1    
    if (c==n):
        print("The number is prime number");
    else:
        print("The number you entered is not a prime number")
        print("it is divisible by ",c)
    

    但是如果你正在寻找一个高效的程序来判断这个数是否是素数,那么你可以参考:https://www.geeksforgeeks.org/python-program-to-check-whether-a-number-is-prime-or-not/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-25
      • 2022-09-23
      • 1970-01-01
      • 1970-01-01
      • 2021-07-06
      • 1970-01-01
      • 2013-09-05
      • 1970-01-01
      相关资源
      最近更新 更多