Generate Prime Numbers Using Python



A prime number is the one that is not divisible by any other number except 1 and itself.

In Python % modulo operator is available to test if a number is divisible by other. 

Assuming we have to find prime numbers between 1 to 100, each number (let us say x) in the range needs to be successively checked for divisibility by 2 to x-1. This is achieved by employing two nested loops.

for x in range(1,101):
for y in range(2,x):
if x%y==0:break
else:
print (x,sep=' ', end=' ')

Above code generates prime numbers between 1-100

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
Updated on: 2020-02-26T12:46:08+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements