python 检查数字是否为素数

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 检查数字是否为素数相关的知识,希望对你有一定的参考价值。

'''FROM SO'''
'''
Check for prime. Only need to iterate up to the square root of n because:
If n = a*b, its either a = b (each a sqrt of n) or a != b. If a != b,
either one of them must be less than the sqrt. Hence, only need to check up
to sqrt of n.
'''
import math
def is_prime(n):
    if n % 2 == 0 and n > 2: 
        return False
    for i in range(3, int(math.sqrt(n)) + 1, 2): # Jump 2 number per iteration, only check odd ones
        if n % i == 0:
            return False
    return True

'''
Note that this code does not properly handle 0, 1, and negative numbers.
We make this simpler by using all with a generator expression to replace the for-loop.
Doens't work with Python 3 though.
'''
import math
def is_prime(n):
    if n % 2 == 0 and n > 2: 
        return False
    return all(n % i for i in range(3, int(math.sqrt(n)) + 1), 2)
    
'''
Jeff Knupp solution
'''
def is_prime(number):
    if number > 1:
        if number == 2:
            return True
        if number % 2 == 0:
            return False
        for current in range(3, int(math.sqrt(number) + 1), 2):
            if number % current == 0: 
                return False
        return True
    return False

以上是关于python 检查数字是否为素数的主要内容,如果未能解决你的问题,请参考以下文章

在Python中检查一个数字是不是是素数[重复]

检查数字是不是为素数

判断任意数字是否为素数

csharp 检查数字是否为素数。从C#的计算机编程基础知识http://www.introprogramming.info/wp-content/uploads/2013/07/Bo

csharp 检查数字是否为素数。从C#的计算机编程基础知识http://www.introprogramming.info/wp-content/uploads/2013/07/Bo

具有素数列表的高效素数分解算法