Write A Python Script To Generate Prime Numbers Up To N

Given an integer and as an input to the Python program, your task is to write a python script to generate all the prime numbers up to N and print them.

Let's try to find the square root of the number, generating the range from 2 to the square root of the number and use this range as the denominator.

 

 

Write A Python Script To Generate Prime Numbers Up To N

 

 

Write A Python Script To Generate Prime Numbers Up To N

Let's take an integer variable named as n,  asking user to enter a number using input function call and then convert it into a using the type conversion. Use  print function to print a user friendly message.

n = int(input("Enter a Number : "))
print(f"Prime Numbers upto {n} is ...")

 





Use the for loop to  iterate in range starting from 2 to N + 1,  and get the number.  within the for loop generate the square root of the number as shown below.

Use another for loop to generate the denominator range from 2 to square root of the number and divide the number by denominator.  If the number is completely divisible by the denominator then break the for loop, using for loop else block print the prime number.

for number in range(2, n+1):
   sqrt = int(number ** 0.5) + 1
   for denominator in range(2, sqrt):
       if number % denominator == 0:
           break
   else:
       print(number, end=" ")

 






Python Script
========================

n = int(input("Enter a Number : "))

print(f"Prime Numbers upto {n} is ...")
for number in range(2, n+1):
   sqrt = int(number ** 0.5) + 1
   for denominator in range(2, sqrt):
       if number % denominator == 0:
           break
   else:
       print(number, end=" ")





Output
==============
Enter a Number : 55
Prime Numbers upto 55 is ...
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53



Output 2
================
Enter a Number : 79
Prime Numbers upto 79 is ...
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79



Conclusion
====================
Execute the above Python program by providing a random integer as an input to the Python program and note down the results.


Commented down below if you have any suggestions to improve the above Python program




Post a Comment

0 Comments