I'm having a problem with problem set 1a. I am outputting lots of prime numbers, but for some reason it is showing a whole bunch of numbers divisible by 5 as primes. I've checked and is seems to be testing if my test number is divisible by 5 but isn't acknowledging that the test number is!!? this is my script: http://pastebin.com/8en99qvn Not a very inspirational start, I'm hoping someone can point me in the right direction!? Thanks.
So I started for scratch and have solved it : http://pastebin.com/EyghwVtY the only thing I don't like is I have to remove 4 from the final number, because my loop will always add 4 onto the result whether it is the final answer or not.
The problem with your code is that when a number is not a prime, it goes on to the next number to be tested, but without resetting the divisor to 2. For example, when your code tests 45, when it gets to divisor 5 it will come to the conclusion that 45 is divisible by 5 and then move on to the next number, 47. However, the first number that the code is going to try to divide 47 by is going to be 5, and not 2. In this way you're sometimes skipping a number's divisors in the test. Also, since you are always adding 2 to the number being tested, it's always going to be an odd number and you don't need to bother starting the divisor from 2.
you could change line 12 to while prime_cand % test_divisor: http://docs.python.org/library/stdtypes.html#truth-value-testing http://pastebin.com/3NHTqTrK http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#testing-for-truth-values
As m_tonho explained, somtimes in your code the test_divisor is skipped to reset it to 2. Try this it will work.
Join our real-time social learning platform and learn together with your friends!