2

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
Bilal Siddiqui
  • 349
  • 3
  • 17
ea192
  • 23
  • 1
  • 4
  • 1
    you shouldn't be using keywords for your variable names. variables like `max`, `min`, `file`, or any other word that your python editor highlights should not be used as variable names. what happens when you want to use the `max` function afterwards? you will get `TypeError: 'int' object is not callable` – aydow Jul 04 '18 at 23:16

2 Answers2

2

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

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)

Live DEMO


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

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

Live DEMO

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Sheshank S.
  • 3,053
  • 3
  • 19
  • 39
0

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:.

Phoenix87
  • 1,003
  • 11
  • 15