So I made this code for problem set 1, which seems to work well to get the 1,000th prime of 7,919. http://pastebin.com/embed_js.php?i=FS89hA3z However, I wondered that it would be able to be more efficient if I made the range skip in intervals of 2, in the form of for a in range(2,b,2): but now the program gives me 1999 instead of 7919. Why would it give me such an answer?
can you explain in words the difference between your original code and the optimized version?
the difference would be as follows, for a in range(2,b): for a in range(2,b,2): I thought that it would let the program to test the values in increment of 2, so it would skip all the even numbers which are definitely not prime.
@feydrax aren't you already doing that by incrementing b by 2? " b += 2 " (line 5)
can you explain in words the difference between your original code and the optimized version
the original one would mean that my code for a in range(2,b): would test "b" with numbers from 2 to (b-1) right? (b%2, b%3, b%4 ......) This allowed me to test for each modular before eventually arriving at the 1000th prime. So I figured that if I make it into for a in range(2,b,2):, I can skip the even numbers, so the test would become ... OHH wait...(b%2,b%4.... is wrong!) no wonder something went wrong with my second version. @bwCA whoops, guess I made a bummer there. Explaining it in words actually helped me solve the problem! Thanks man!
It helps if you write down in words what you are trying to do and the steps it will take to accomplish it - before you start coding. It helps to organize your thoughts. Then you try to turn that into code, breaking it into logical chunks if possible. as you debug, you can refer to what you originally wrote and modify that as as necessary. The text version will will document your code as well as help you write it.
@bwCA Thanks for your help! Really appreciate it. This piece of advice is really helpful for beginners like me. I'm going to be more careful on these kinds of problems next time.
Join our real-time social learning platform and learn together with your friends!