Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save FaradayLab/be1069068d143978a6410eb822b457ce to your computer and use it in GitHub Desktop.
Save FaradayLab/be1069068d143978a6410eb822b457ce to your computer and use it in GitHub Desktop.
Checks if a number is prime in a single line of Python
# Correcting exclusion of last factor that needs to be checked
# Micro optimization of code
# Code syntax/format preference changes
# Might as well be able to check any number
# 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
from math import sqrt
if a<2 or a!=2 and sum([a%f==0 for f in (2,*range(3,int(sqrt(a))+1,2))]):
print('Number is not prime')
else:
print('Number is prime')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment