Python Prime number checker [duplicate]
You need to stop iterating once you know a number isn't prime. Add a break
once you find prime to exit the while loop.
Making only minimal changes to your code to make it work:
a=2num=13while num > a : if num%a==0 & a!=num: print('not prime') break i += 1else: # loop not exited via break print('prime')
Your algorithm is equivalent to:
for a in range(a, num): if a % num == 0: print('not prime') breakelse: # loop not exited via break print('prime')
If you throw it into a function you can dispense with break
and for-else:
def is_prime(n): for i in range(3, n): if n % i == 0: return False return True
Even if you are going to brute-force for prime like this you only need to iterate up to the square root of n
. Also, you can skip testing the even numbers after two.
With these suggestions:
import mathdef is_prime(n): if n % 2 == 0 and n > 2: return False for i in range(3, int(math.sqrt(n)) + 1, 2): 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.
import mathdef 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))
def isprime(n): '''check if integer n is a prime''' # make sure n is a positive integer n = abs(int(n)) # 0 and 1 are not primes if n < 2: return False # 2 is the only even prime number if n == 2: return True # all other even numbers are not primes if not n & 1: return False # range starts with 3 and only needs to go up # the square root of n for all odd numbers for x in range(3, int(n**0.5) + 1, 2): if n % x == 0: return False return True
Taken from: