Hello , I just wrote the script for ps1a . Looking forward to your critique to improve .
I would separate out the loop that counts how many primes you've encountered from the loop that tests an individual number to see whether or not it is prime. This makes the logic of each loop clearer to follow. In addition, there's a bug in your code; it printed the 1001st prime instead of the 1000th. Here is my refactoring: def isPrime(n): divisor = 2 while divisor < n: if n % divisor == 0: return False else: divisor += 1 return True pcount = 0 testno = 1 while pcount < 1000: testno += 1 if isPrime(testno): pcount += 1 print('The 1000th prime is ', testno)
ditto - looks good but 3 is either your zeroeth or first prime, you miss 2 and 1(?) http://www.ipaste.org/L6
@ktklown: Nice and neat... though couldn't you replace line 3 with "while n/divisor >=divisor:"? My first attempt was much more clumsy. But I still can't really figure out why it doesn't work... despite it's clumsiness. Can you help? (q is my divisor variable) def primetest(n): if n % q == 0: q = 2 primetest(n+1) elif n / q >= q: tally = tally + 1 print 'new prime: ', n print 'new tally: ', tally if tally==1000: print n, "is the 1000th prime number" return else: q = 2 primetest(n+1) n = 3 tally = 1 q = 22 primetest(3)
pls use a code pasting site - http://dpaste.com/667494/ if you post to an old thread a lot of ppl won't see it what seems to be the problem?
Thank you ktklown and bwCA . The reason i din't use the functions because they weren't covered in the first lectures . ty for pointing out the bugs i fixed them now . Ill try ps1b now :)
Join our real-time social learning platform and learn together with your friends!