Ask your own question, for FREE!
MIT 6.00 Intro Computer Science (OCW) 9 Online
OpenStudy (anonymous):

hi! prob 1: running in a loop. i don't understand why my code is not working. could someone help? counter = 1 n = 1 while counter < 4: n += 2 divisors = range(1,n,2) b = False for d in divisors: b = (n%d == 0) if b == True: break else: counter += 1 print n else: print n + ' is the 1000th prime number'

OpenStudy (espex):

What is the output or error you are getting? As I read this you have an else statement hanging, and you could take the assignment to b completely out and just use it as the conditional for your if statement. I'm not quite certain what you are accomplishing with the for loop.

OpenStudy (anonymous):

it's supposed to find the first three prime numbers only actually. basically, the for loop is dividing the candidate n by all numbers between 1 and itself, increment 2. if any of those divisions doesn't yield a remainder, then it'S NOT a prime number... and here's the mistake. it must be divisors = range(3,n-2,2) and it works! thanks for your time though!

OpenStudy (vaboro):

you check if next prime candidate is divisible by all previous odd numbers starting from 3, range(3, n-2, 2), but according to definition of prime you need to divide by all previous prime numbers because not all odd numbers are primes, and division can be stopped as soon as divisor equals the square root of the candidate (see Wikipedia's definition of primes)

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!