0

Hi I am trying to find prime numbers from 1 to n, where is provided by user, I searched different sources on google I am working on the same logic but my logic shows all even numbers instead of prime

# prime number calculator

import time
userInput = int(
    input('Please Choose the number to find if its Prime or not: '))

flag = False


for i in range(2, userInput+1):
    if userInput % i == 0:
        flag = True
        break


if flag:
    print(f'{userInput} is not prime')
else:
    print(f'{userInput} is Prime')

choice = 'none'

while choice not in ['Y', 'N']:
    choice = input(
        f'want to display all prime numbers between {userInput} (y,n): ').upper()
        

listOfPrimes = [2,]

if choice == 'Y':
    for num in range(2, userInput+1):
        for i in range(2, num):
            if num % i == 0:
                break
            else:
                listOfPrimes.append(num)
                break
else:
    time.sleep(1)
    print('Good Bye')


print(listOfPrimes)

output - [2, 3, 5, 7, 9, 11, 13, 15, 17]

I am new to programming not sure where my logic fails

Myk1709
  • 25
  • 5
  • Take a look at this question. It might help you: https://stackoverflow.com/questions/68637037/does-anyone-know-why-my-program-doesnt-generate-the-correct-amount-of-prime-num – Tranbi Aug 04 '21 at 10:37
  • A search gives a lot of similar topics https://stackoverflow.com/search?q=python+Prime+numbers – Алексей Р Aug 04 '21 at 10:37
  • 1
    Your first loop (checking a specific number) is also wrong. If the user enters, say, `5` then you run from 2 to 5 (inclusive) and check `userInput % i == 0`, the last iteration of which would be `5 % 5 == 0`, which will of course be true and the number will be reported as not prime. – Kemp Aug 04 '21 at 10:38

1 Answers1

0

Your inner for loop is always going to execute a break on its first iteration, whether or not the if condition is false or true. In either case you break. So that means the loop will only do one iteration.

The second break should not be there. In fact, you should detect when the loop completes without doing the first break. For that, Python allows an else to be part of the for, which will exactly capture that case: when the loop exits normally (not via break) it will enter such an else:

for i in range(2, num):
    if num % i == 0:
        break
else:
    listOfPrimes.append(num)

Secondly, you should not include the number itself in the outer loop. You have this error also in the first part of the code. So change:

for i in range(2, userInput+1):

to

for i in range(2, userInput):
trincot
  • 317,000
  • 35
  • 244
  • 286