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") |
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)
Well spotted @FaradayLab, thank you
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
def prime_number():
print("This program determines if a number is prime or not.")
print("This program will only accept integers.")
number = input("Please enter the number you want to check over here: ")
number = int(number)
if number > 0:
if number == 3:
print("The number is prime.")
choice = input("Do you want to enter another number? Type 'continue' if you do & 'exit' if you don't: ")
if choice == 'continue':
prime_number()
if choice == 'exit':
return
if choice != 'continue' and choice != 'exit':
print("You have not entered a valid choice so the program will stop running.")
return
if number == 1:
print("One is neither prime nor composite.")
choice = input("Do you want to enter another number? Type 'continue' if you do & 'exit' if you don't: ")
if choice == 'continue':
prime_number()
if choice == 'exit':
return
if choice != 'continue' and choice != 'exit':
print("You have not entered a valid choice so the program will stop running.")
return
if number == 2:
print("The number is prime.")
choice = input("Do you want to enter another number? Type 'continue' if you do & 'exit' if you don't: ")
if choice == 'continue':
prime_number()
if choice == 'exit':
return
if choice != 'continue' and choice != 'exit':
print("You have not entered a valid choice so the program will stop running.")
return
prime_number()
another version
yours is creative though