Last active
May 23, 2021 11:30
-
-
Save cescapa/c655e8e0c1558660150f to your computer and use it in GitHub Desktop.
Checks if a number is prime in a single line of Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Assumes that "a" contains an integer > 2 whose primality needs to be verified | |
# The algorithm builds a list of factors including the number 2 and all odd numbers | |
# up to the square root of "a", and then checks if any of those numbers divides "a" | |
# without a remainder - if so then "a" is not prime, else it is | |
if sum([ True if a%factor == 0 else False for factor in ( [2] + list(range(3,int(math.sqrt(a))+1,2) )) ]): | |
print("Number is composite") | |
else: | |
print("Number is prime") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This doesn't work. For instance, 323. 323/17 = 19. The
int(math.sqrt(a))
is 17 but range excludes 17. One revision needs to be made.list(range(3,int(math.sqrt(a)),2)
needs to be:list(range(3,int(math.sqrt(a))+1, 2)