在 Python 中查找素数 [英] Finding prime numbers in Python

查看:47
本文介绍了在 Python 中查找素数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个函数,is_prime(),它接受一个整数 n > 1 并返回 TRUE 如果数字是素数并且 否则为 False.但是当我输入 2 时,它总是返回 False.有没有办法纠正这个?

I need to write a function, is_prime(), which takes in an integer n > 1 and returns TRUE if the number is a prime number and False otherwise. But when I input 2, it always returns False. Is there anyway to correct this?

def is_prime(x):
    if(x > 1):
        for i in range(2,x+1):
            if( x % i == 0):
                return False
            else:
                return True
    else:
        return False

推荐答案

两个问题:
第一个问题是范围包括数字本身,这意味着它总是会返回 true(对于数字 > 1),因为素数可以自除...

Two issues:
First issue is that range includes the number itself, which means that it will always return true (for numbers > 1) because prime numbers can divide themselves...

修正:将range(2,x+1)改为:range(2, x)

第二个问题,第一个 else 应该与 for 对齐(我们只有在尝试所有数字并确保它们都没有划分 后才返回 truex)

Second issue, the first else should be aligned with the for (we return true only after trying all the numbers and making sure that none of them divides x)

固定代码:

def is_prime(x):
    if x > 1:
        for i in range(2,x):
            if x % i == 0:
                return False
        else:
            return True
    else:
        return False

这篇关于在 Python 中查找素数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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