Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I was not able to print a series of prime integers from one to a hundred. Here's what I have written; it is printing all the odd numbers instead of primes:

for num in range(1, 101):

    for i in range(2, num):

        if num % i == 0:

            break

        else:

            print(num)

            break

1 Answer

0 votes
by (107k points)
edited by

First of all, try to check all numbers from 2 to n-1. If n is divided by any of the numbers, it is not prime. If a number is prime, print it.

for num in range(2,101):

    prime = True

    for i in range(2,num):

        if (num%i==0):

            prime = False

    if prime:

       print (num)

More pythonic way is:

for num in range(2,101):

    if all(num%i!=0 for i in range(2,num)):

       print (num)

Or in this manner:

import math

for num in range(2,101):

    if all(num%i!=0 for i in range(2,int(math.sqrt(num))+1)):

       print (num)

An improved version is:

import math

print 2

for num in range(3,101,2):

    if all(num%i!=0 for i in range(2,int(math.sqrt(num))+1)):

       print (num)

Kindly check Python blog will help you get a better understanding of Automate Your Coding with Python!

Related questions

0 votes
1 answer
asked Dec 8, 2020 in Python by ashely (50.2k points)
0 votes
1 answer
asked Feb 9, 2021 in Python by ashely (50.2k points)
0 votes
1 answer
0 votes
1 answer
asked Dec 17, 2020 in Python by ashely (50.2k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...