Skip to content

Instantly share code, notes, and snippets.

@cescapa
Last active May 23, 2021 11:30
Show Gist options
  • Save cescapa/c655e8e0c1558660150f to your computer and use it in GitHub Desktop.
Save cescapa/c655e8e0c1558660150f to your computer and use it in GitHub Desktop.
Checks if a number is prime in a single line of Python
# 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")
@FaradayLab
Copy link

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)

@cescapa
Copy link
Author

cescapa commented Sep 25, 2020

Well spotted @FaradayLab, thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment