Header Ads Widget

Python program to print the entire prime no between 1 and 300

 

Python program to print the entire prime no between 1 and 300

Here we have to write a Python program that will print all the prime number between 1 to 300 . So what is prime number ? A number is known as prime number if it is only divisible by 1 and itself . 

Python  program to print the entire prime no between 1 and 300

The objective of the code is to print all the prime numbers between 1 to 300 .

Algorithm:

  1. Start from 1 and iterate through each number up to 300.
  2. For each number, check if it is prime or not.
  3. To check if a number is prime or not, divide the number by all numbers from 2 to the number/2.
  4. If the number is divisible by any of the numbers in the range, it is not a prime number.
  5. If the number is not divisible by any of the numbers in the range, it is a prime number.
  6. Print all the prime numbers found during the iteration.

Code(Python):-

# Function to check if a number is prime or not
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n/2)+1):
if n % i == 0:
return False
return True

# Print all prime numbers between 1 and 300
for i in range(1, 301):
if is_prime(i):
print(i, end=" ")


Output:-

1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107
109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223
227 229 233 239 241 251 257 263 269 271 277 281 283 293

Explanation:

The above program starts from 1 and iterates through each number up to 300. For each number, it checks if the number is prime or not by calling the is_prime function. If the number is prime, it prints the number.

The is_prime function takes a number as input and checks if it is prime or not. If the number is less than or equal to 1, it is not prime. Otherwise, the function iterates through all numbers from 2 to the number/2 and checks if the number is divisible by any of them. If the number is divisible by any of the numbers in the range, it is not a prime number, and the function returns False. If the number is not divisible by any of the numbers in the range, it is a prime number, and the function returns True.

If the number is prime, the program prints the number using the print statement. The end parameter is used to specify the separator between the printed numbers. Finally, the program terminates.

Recommended Post :-

HCL Coding Questions:-

Capgemini Coding Questions:-

Companies interview:-

Full C course:-    

Key points:-

Cracking the coding interview:-

 Array and string:-

Tree and graph:-

Hackerearth Problems:-

Hackerrank Problems:-

Data structure:-

 MCQs:-