-2
n= int(raw_input("Number? "))
for x in range (2, n+1): 
    for y in range (2, x+1):
    if x < n+1 and x % 2.0 > 0 and x % 3.0 > 0 and x%y > 0:
            print x
            x = x + 1  

Hello there. I need to create a SIMPLE python program, which lists all the prime numbers up to and inclusive of the input number. For example, if you input 10, it would produce 2, 3, 5 ,7

I'd prefer to keep it simple, and do not use more advanced functions such as def, break. Nested loops are PREFERED.

The code above does NOT work, it contains non-primes such as 25 and 91.

Please help!

Jeff
  • 11,233
  • 10
  • 44
  • 85
Elf Demon
  • 1
  • 1
  • 1

2 Answers2

2

Your code concludes that a number x is prime if it's not divisible by at least one y, whereas it needs to check that it's not divisible by all y.

You also need to carefully check the bounds of the y loop.

On a side note, I suggest you get rid of the floating-point calculations (e.g. x % 2.0) and stick to integer maths. It probably doesn't matter here, but has the potential of opening a large can of worms.

NPE
  • 438,426
  • 93
  • 887
  • 970
1

You must reverse your thinking. Your code reports a number as soon as it is a non-multiple of some y. Instead, you should non-report a number as soon as it is a multiple of some y.

n= int(raw_input("Number? "))
for x in range (2, n + 1):
    prime= True
    for y in range (2, x):
        if x % y == 0:
            prime= False
    if prime:
        print x
Yves Daoust
  • 48,767
  • 8
  • 39
  • 84
  • I understand what you are saying Daoust. Problem is, I don't know how to fix it. And no, this is NOT a duplicate. I am not allowed to use any advanced function in Python. I can only use functions like while loop, for loop, isprime, math.sqrt etc. – Elf Demon Mar 12 '13 at 01:37
  • Don't shout at me, the comment about duplicate was from someone else. – Yves Daoust Mar 12 '13 at 07:26