简体   繁体   中英

Determining Prime numbers using nested while loops in Python

I have this prime numbers program to solve: given a max input, I am to determine all the prime numbers between 2 and the max input inclusive, using a while loop inside a while loop.
I know this would be simpler using a range and/or math functions but for the purposes of this assignment I need to use while-loops.

Testing the code below with max = 5 outputs 2,3,4 .
Correct output is 2,3,5 .

max = int(input('Enter the max integer: '))
start_number = 2

while start_number <= max:
    interval_number = start_number
    while interval_number <= max: 
        if max % interval_number != 0: 
            print(interval_number)
            interval_number += 1
    start_number += 1

Might be easier to use for loops. This program assumes that a number is prime, and then checks everthing up to the number.

Live demo: https://repl.it/repls/MidnightblueWobblyPlane

max = int(input('Enter the max integer: '))
for number in range(2, max+1): 
    is_prime = True
    for interval_num in range(2, number):
        if number % interval_num == 0:
            is_prime = False
            break

    if is_prime:
        print(number)

If you must however, use while loops, here you go. It's the same logic:

Live demo: https://repl.it/repls/BlandQualifiedBetatest

max = int(input('Enter the max integer: '))
possiblePrime = 2
while possiblePrime < max+1: 
    isPrime = True
    num = 2
    while num < possiblePrime:
        if possiblePrime % num == 0:
            isPrime = False
            break
        num += 1

    if isPrime:
        print(possiblePrime)

    possiblePrime += 1

Hope it helped!

The best way would be to use the Sieve of Eratosthenes . If you want to use two nested while loops, then consider that for each number you really need to check for the divisibility up to the square root of the current number. Hence somewhere you will have a condition of the type while factor * factor <= current_number: .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM