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

Can someone tell me why every number is being output in my code? http://codepad.org/bCGxY0BN

OpenStudy (anonymous):

Your code is actually returning every time m==inp, that is, every time that happens, it prints, whether or not it checks for divisibility, i.e.: if inp = 4(second time through the loop), your code will check 4%3 != -> m+=1, then 4%4 == 0 -> print inp, and, because of that, it prints every increment.

OpenStudy (anonymous):

Alright, I moved the print section to be included within the divisibility statement and I still have the same problem. Also, whiles follow order from top to bottom correct? So should it not check for divisibility first, if it a%b==0 then the while statement should break before the print statement initiates? Or is Python nonlinear? Here is the code after the edit. http://codepad.org/AD7hSHs4

OpenStudy (anonymous):

This site is so bugged T_T.. I will retype my answer.

OpenStudy (anonymous):

I think your algorithm is wrong; your code is actually returning the same thing because you didn't change it. Try to loop with only odds first (or x%2 != 0 or x = 1, then x+=2) and then check for divisibility up to (and including) sqrt of candidate for prime. One way of writing the program that I found straightforward even thought not efficient is to generate a list of odds and then iterating through the list, checking for divisors. Again, it's quite inefficient in terms of complexity, but it is easy to code it up and gives you a safe place to start improving the code.

OpenStudy (anonymous):

First write the code that tests whether a single number is prime. Ignore the requirement to find the 1000th prime. Make sure that you can get that code to work reliably. THEN start working on the bigger problem.

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!