I wrote a program in Python to generate prime numbers
here is the program
def genPrimes(n):
primes = [2] # primes generated so far
last = 3 # last number tried
while last <= n:
for p in primes:
if last % p == 0 and math.sqrt(p) <= last:
break
else:
primes.append(last)
last += 2
return primes
This program is producing a right answer. If you see the indentation for else: statement it is wrongly placed. if i try to place the else statement in if block interpreter is showing memory error. Can anyone tell why this is happening.
Thanks in advance
Maries
The
elseis actually attached to theforloop, and executes if the program doesn’t break out of the loop. In your case, it executes if none of the primes divide into the number, so the number is prime and gets appended to the list.See also the documentation.