Prime Numbers question: im having trouble writing a program that finds all prime numbers to a n'th number and prints them. Heres what I have so far, if someone could help and explain what im doing wrong, it would be appreciated: def isPrime (n): primeList = [2] for i in range (3, n): if n%2 == 0 or n%3 == 0: break else: primeList.append(i) break return (primeList)
All non-prime numbers will factor down to prime numbers. Therefore that list of primes that you're building, ( at least the ones less than the square root of the number you're checking ), is all you need to check.
your condition for a number to be prime is that the residual is 0 when divided by 2 or 3, so if someone enters 30 as the "n", for example, the number 25, which is divisible by 5, will be appended to your list because it meets these conditions. Instead of writing, n%2==0 or n%3==0, try writing a loop that checks that the new value of "i", is not divisible by any of the prime numbers in your list. Kind of like, for i in range (1, size(primeList)): if n%primeList(i)==0 break else continue
Join our real-time social learning platform and learn together with your friends!