开发者社区> 问答> 正文

该代码是否正确以检查数字是否为质数?

以下是您尝试发布的格式的代码:

user_number = int(input("Enter a number: "))
a = list(range(2, user_number))
def prime(x):
    for e in a:
        if user_number % e == 0:
            print(str(user_number) + " is not a prime number.")
            break
        else:
            print(str(user_number) + " is a prime number.")
            break
prime(user_number)

展开
收起
几许相思几点泪 2019-12-29 18:52:22 866 0
1 条回答
写回答
取消 提交回答
  • 更正您的代码,

    user_number = int(input("Enter a number: "))
    a = list(range(2, user_number))
    def prime(x):
        isPrime = True # Assumne that the number is prime
        for e in a:
            if user_number % e == 0: # If divisible, it's not a prime number
                isPrime = False
                break
        if isPrime:
            print(str(user_number) + " is a prime number.") # Not divisible by any number in range [2,user_number), i.e. a prime number
        else:
            print(str(user_number) + " is not a prime number.")
    
    prime(user_number)
    
    2019-12-29 18:52:37
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载