what's wrong with this (trying to find a prime number) import math candidate=29 if (candidate/2)*2 == candidate: print candidate, 'is even' else: print candidate, 'is odd' for i in range(2,candidate): if candidate % i == 0: print candidate, 'is not a prime' else: print candidate, 'is a primo'
Why not use the following as the first line? if (candidate%2) != 0:
Oops, that should be the reverse: if (candidate%2) == 0:
That's better than expanding to if candidate % i == 0?
You don't need to import math, but, more importantly, you must recognise what `for` does. It takes each item in a sequence, in order, the first, the second and so on, and assigns them, one at a time to a variable which you name anything you like. You called it `i`, but you can call it anything, `each` is common. `in` is obvious and then, on the end, you need a sequence. The range() function returns a sequence, a list of integer numbers in the range. So for each in 'abc': print each print '...' would output a ... b ... c ... because the for loop assigns the first item in the sequence, the 'a', to the variable `each`, so `each` now evaluates to a single character string, 'a'. Then it goes through the indented block, print each, so it prints the letter a, then print three dots, then the interpreter reaches the end of the block so it goes back to the top and assigns the next thing in the sequence to `each`, the character 'b' and so on until it has done this once for each item in the sequence. Because range returns a sequence, a list of numbers, you can iterate across them one by one, which you are doing with for i in range(2, candidate): This enables you to test whether candidate % i == 0 over and over again. Once with `i` evaluating to 2, then with it evaluating to 3 and so on. It is only once you have tried to divide `candidate` by every possible value for `i` and still have got no result that has a remainder of 0, that you know that `candidate` is prime. You must exhaust every possible value for `i` before you can know that `candidate` is prime. This is the bit you are struggling with. Try here for an example to work from http://pastebin.com/KU0CXFx3
Your program is horribly in-efficient all you have to check are primes from 2 to the sqrt of the candidate. No reason to check all numbers.
Join our real-time social learning platform and learn together with your friends!