Ok, so here is my attempt at problem set 1. Can anyone tell me where I went wrong? import math number=1 primes = [2] moduli=[1] test=3 while number <= 1000: for prime in primes: if (test/prime)>=2: m=test%prime moduli.append(m) moduli.sort() for item in moduli: if 0==item: moduli=[] test=test+2 else: primes.append(test) test=test+2 number=number+1 print primes[1000]
ok, so from my understanding you're divising test variables by all primes found so far, right? when I ran your code it gave me 2039 as the 1000th prime which is too low
it seems that by div/mod by primes results in the code finding primes which actually arent
yeah - if we are testing number x, then it is prime if it is NOT evenly divisible by any prime lower than x/2
yeah
got it working import math n=1 primes = [2] check=0 test=3 while n <= 1000: for prime in primes: if test%prime==0: check=1 if check==1: test=test+2 check=0 else: primes.append(test) test=test+2 check=0 n=n+1 print primes[999]
just ran your code again to print out the primes when it finds them and it gives e.g. 15, 21,27..all divisible by 3, which is in the list as well - seems like that's responsible
yeah, i got rid of the mod check list, and just had it be a binary result - if one of the primes divides evenly into the test number, it changes the check number to 1, which means test number is not prime
cool! I like your solution - mine was much more complicated - gonna take a closer look at it :)
thanks :) . mind posting your sol'n?
sure: primecount = 0 candidate = 1 while primecount < 999: candidate = candidate +2 divisor = 3 not_prime = False while (divisor < candidate/2) and (not_prime == False): if candidate%divisor == 0: not_prime = True ## print candidate ## print (' is not a prime') divisor = divisor+2 if not_prime == False: ## print (candidate) ## print ('is prime') primecount = primecount +1 print candidate
didn't know about division by primes so divided by all candidates/2 up to the current every time
looks very similar to mine, except for the primes thing. nice.
thx
Join our real-time social learning platform and learn together with your friends!