在 Python 中将数字是否为素数作为布尔值返回 [英] Returning whether or not a number is prime as a Boolean in Python

查看:48
本文介绍了在 Python 中将数字是否为素数作为布尔值返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于上下文,我正在尝试使用 Python 解决 Project Euler 问题 3:

For context, I am trying to solve Project Euler problem 3 using Python:

600851475143 的最大质因数是多少?

What is the largest prime factor of the number 600851475143?

作为第一步,我正在尝试编写一个函数,该函数将一个数字是否为素数作为布尔值返回.我做了第一次尝试,并检查了以前是如何编写的.我最终得到了以下代码:

As a first step to this, I am trying to write a function that returns whether or not a number is prime as a Boolean. I made a first attempt, and checked out how this has been written previously. I have ended up with the following code:

def isprime(x):
    limit = x**0.5
    i = 2

    if x < 2:
        return False
    elif x == 2:
        return True
    else:
        while i <= limit:
            if x%i == 0:          
                return False
                i = i + 1       
            else:
                return True

由于某种原因,上面的代码不能完美运行.例如,isprime(99) 将返回 True.

For some reason, the code above does not work perfectly. For example, isprime(99) would return True.

请问,有人能帮我理解为什么这不起作用吗?我试图避免只是复制和粘贴别人的代码,因为我想确切地了解这里发生了什么.

Please, can someone help me understand why this isn't working? I am trying to avoid just copying and pasting someone else's code, as I want to understand exactly what is going on here.

对我来说,问题似乎出在最后的 else 语句上.我这样说是因为逻辑读取在 x%i == 0 的情况下,这个数字不是质数"但它没有明确说明在没有 的情况下该怎么做x%i 迭代 == 0.

To me, it looks like the issue is with the final else statement. I say this because the logic reads "in the event that x%i == 0, this number is not prime" but it doesn't explicitly say what to do in the event that no x%i iterations == 0.

对此的任何帮助将不胜感激!我不一定要寻找最干净、最简洁的方式来执行此操作,而更多地只是尝试首先使此代码工作.

Any help on this would be appreciated! I'm not necessarily looking for the cleanest, neatest way of doing this, but more just trying to first make this code work.

推荐答案

只是为了展示一个替代方案,如果操作 (x % i)等于零.如果它从未发生过,它将是一个质数.

Just to show an alternative, what you could do is checking from number 2 to your number if the operation (x % i) is equal to zero. If it never happend, it will be a prime.

def isprime(x):
   # check for factors
   for i in range(2,x):
       if (x % i) == 0:
           return False
   else:
       return True

print(isprime(99))

这篇关于在 Python 中将数字是否为素数作为布尔值返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆