Write a program primes.py that reads a positive integer from standard input, and determines whether or not the number is prime.
Question
Write a program primes.py
that reads a positive integer from standard input, and determines whether or not the number is prime.
Solution
Sure, here is a simple Python program that checks if a number is prime:
def is_prime(n):
if n <= 1:
return False
elif n <= 3:
return True
elif n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
n = int(input("Enter a positive integer: "))
if is_prime(n):
print(n, "is a prime number")
else:
print(n, "is not a prime number")
This program works by checking divisibility of n
starting from 2 up to the square root of n
. If n
is divisible by any of these numbers, then it is not a prime number. If n
is not divisible by any of these numbers, then it is a prime number.
Similar Questions
Write a python script that accept a number from the user and display a prime number from 1 to the value:
What are looping statements. Write a program to check whether a number is prime no. or not.
Please create a pseudocode function that can check if a given number n is prime or not, where n > 1.
Write a single line Python code to print all the prime numbers between 1 and 200.
Write a program to count the number of prime factors of a given positive integer and calculate the difference between the number and the lowest prime factor.
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.