The prime number is also referred to as prime numbers , which is thenumber of natural numbers greater than 1, except 1 and the number itself, which cannot be divisible by other natural numbers (it can also be defined as only 1 and the number itself two factors). If the natural number greater than 1 is not prime, it is called composite.
Use Python to determine whether a number is prime.
The first method is divisible by dividing the number within the number range, the efficiency is very low, when the number is large time-consuming, the code realizes:
def is_prime (n): if n = = 2: return True if n 2 = = 0 or n <= 1: return False sqr = Int (MATH.SQRT (n ) + 1 for divisor in range (3, SQR, 2): if n% divisor = = 0: return False return True
The second approach is to use algorithms to optimize the entire logic and execution process, filtering out all primes within N, by defining an array, generating n*true elements, and implementing the Code:
def prime_sieve (n): sieve_lst = [True] * n sieve_lst[0] = False # First and second not a prime number, set to False sieve_lst[1] = False for I in range (3, int (MATH.SQRT (n)) +1): pointer = i * # # of multiples within n digits, all set to False while pointer < n:< C8/>sieve_lst[pointer] = False pointer + = i primes = [] for x in range (n): if sieve_lst[x]: Primes.append (i) print primes return Primesprime_sieve (33) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
This algorithm comes from thebook "Hacking Secret ciphers with Python"
Determine if any number is prime