Back

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

I am working on an exercise in Python, in that I need to write a code using loops to find prime numbers. For loop is working fine for me.  When I am executing the same code with the while loop, it was also working, but it is returning me a few incorrect numbers.

import math

# looking for all primes below this number

max_num = int(input("max number?: "))

primes = [2]  # start with 2

test_num = 3  # which means testing starts with 3

while test_num < max_num:

    i = 0

    # It's only necessary to check with the primes smaller than the square

    # root of the test_num

    while primes[i] < math.sqrt(test_num):

        # using modulo to figure out if test_num is prime or not

        if (test_num % primes[i]) == 0:

            test_num += 1

            break

        else:

            i += 1

    else:

        primes.append(test_num)

        test_num += 1

print(primes)

When I am passing max_num=100, it is returning:

[2, 3, 5, 7, 9, 11, 13, 17, 19, 23, 25, 29, 31, 37, 41, 43, 47, 49, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

Kindly guide me. 

1 Answer

0 votes
by (108k points)

I think your code is missing the family of prime squares. What you need to do is include the square root. You just need to replace '<' with '<=' as your stopping condition.

But suppose changing the stopping condition to

primes[i] * primes[i] <= test_num

With this analysis, you don't dip in and out of floating-point data.

Interested in learning Python? Enroll in our Python Course now!

Related questions

0 votes
1 answer
asked Jan 5, 2021 in Python by ashely (50.2k points)
0 votes
1 answer
asked Dec 8, 2020 in Python by ashely (50.2k points)

Browse Categories

...