# Write a function in python which accept a number from user to return True, if the number#is a prime number else return False. Use this function to print all prime numbers from 1#to 100.
Question
Write a function in python which accept a number from user to return True, if the number#is a prime number else return False. Use this function to print all prime numbers from 1#to 100.
Solution
Sure, here is a Python function that checks if a number is prime and then uses this function to print all prime numbers from 1 to 100.
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
for num in range(1, 101):
if is_prime(num):
print(num)
In the is_prime function, we first handle the special cases of numbers less than or equal to 1 (which are not prime) and numbers less than or equal to 3 (which are prime). Then we check if the number is divisible by 2 or 3, in which case it is not prime. If it passes these checks, we then check divisibility for all numbers up to the square root of the number (since a larger factor of the number would be a multiple of some smaller factor that has already been checked). If the number is not divisible by any of these, it is prime.
Then we use this function in a loop from 1 to 100 to print all prime numbers in this range.
Similar Questions
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.