Python Forum

Full Version: Prime Numbers
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
import math
prime_count = 0
#This Code checks if the n integer is prime!
def is_prime(n):
    if n % 2 == 0 and n > 2: # 2 is the only even prime
            return False
    return all(n% i for i in range(3, int(math.sqrt(n)) + 1, 2))

print(is_prime(5))

import sys
prime_count = 0 #prime counter
for arg in sys.argv[1:]: #for all the arguments (typed) in the command
    n = int(arg)
    if (is_prime(n)):
        print('The Number ',n,' is Prime!') #Displays the prime number if True
        prime_count += n #prime_count = primecount + 1

print('Total Primes:', prime_count)
I understand the whole code just there's this bit that I don't understand:
return all(n% i for i in range(3, int(math.sqrt(n)) + 1, 2))
And it didn't work any other way it would start giving me 4 and 8 as prime numbers Think

Anyone care to explain?
First you get the square root of n (math.sqrt(n)). If n has any factors other than itself and 1 (that is, if n is composite/non-prime), one of those factors will be less than it's square root. You convert that float to an int, because range only takes ints. This lowers the value, so you add one to make sure the square root is included.

Now, you've already checked for two being a factor, which counts as checking all the even factors. So you get the range from 3, to square root, taking every second number. So 3, 5, 7, ... This gives you all the odd factors. You loop through those odd factors with a comprehension statement (n % i for i in range(...)), getting n % i for each odd factor i. Since n % i is non-zero if i is not a factor of n, and non-zeros evaluates as True, all() returns True if none of the odd factors are actually factors of n. (all returns True if all of the items in the sequence passed to it are True, and False if any of them are false.)