开发者社区 问答 正文

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

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

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 886 分享
分享
版权
举报
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 举报
    赞同 评论

    评论

    全部评论 (0)

    登录后可评论
问答地址:
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等