📜  用于检查素数的Python程序

📅  最后修改于: 2022-05-13 01:56:56.748000             🧑  作者: Mango

用于检查素数的Python程序

给定一个正整数,检查该数是否为素数。素数是一个大于 1 的自然数,除了 1 和它自身之外没有正除数。前几个素数的例子是 {2, 3, 5,

例子:

Input:  n = 11
Output: true

Input:  n = 15
Output: false

Input:  n = 1
Output: false

学校方法:

# A school method based Python3 
# program to check if a number
# is prime
  
def isPrime(n):
  
    # Corner case
    if n <= 1:
        return False
  
    # Check from 2 to n-1
    for i in range(2, n):
        if n % i == 0:
            return False;
  
    return True
  
# Driver Program to test above function
print("true") if isPrime(11) else print("false")
print("true") if isPrime(14) else print("false")
  
# This code is contributed by Smitha Dinesh Semwal

输出:

true
false

该解决方案的时间复杂度为 O(n)


优化的学校方法:

# A optimized school method based  
# Python3 program to check 
# if a number is prime 
    
    
def isPrime(n) : 
    # Corner cases 
    if (n <= 1) : 
        return False
    if (n <= 3) : 
        return True
    
    # This is checked so that we can skip  
    # middle five numbers in below loop 
    if (n % 2 == 0 or n % 3 == 0) : 
        return False
    
    i = 5
    while(i * i <= n) : 
        if (n % i == 0 or n % (i + 2) == 0) : 
            return False
        i = i + 6
    
    return True
    
    
# Driver Program  
    
if(isPrime(11)) : 
    print(" true") 
else : 
    print(" false") 
        
if(isPrime(15)) : 
    print(" true") 
else :  
    print(" false") 
        
        
# This code is contributed  
# by Nikita Tiwari. 

输出:

true
false

请参阅有关 Primality Test | 的完整文章Set 1 (Introduction and School Method) 了解更多详情!