[Tutor] Help

Andre Engels andreengels at gmail.com
Tue Jul 13 12:22:40 CEST 2010


On Tue, Jul 13, 2010 at 11:50 AM, Dipo Elegbede <delegbede at dudupay.com> wrote:
> I was trying to write a code that prints prime numbers between 1 and 20.
>
> I have by myself seen that something is wrong with my code and also my
> brain.
>
> Could anyone be kind enough to tell me what to do....
>
> Where I am confused is how to test for other numbers without one and the
> number itself. It turns out that all numbers pass the condition I set so
> that would presuppose that all numbers are prime which is not.
>
> How exactly can I get it to run checks with other numbers such that it
> doesn't include the number itself and 1.
>
> The code is as follows:
>
> for i in range(1,20):
>
>     if float(i) % 1 == 0 and float(i) % i == 0:
>         print i, 'is a prime number'

Your code only checks whether the number divides by 1 and itself. It
should check the numbers in between, and if _any_ divides the number,
decide it is not a prime number. This is best done in a separate
function (note: I am writing it here for clarity of the underlying
algorithm, there are various ways in which it could be made faster,
shorter or more Pythonic):

def isPrime(n):
    divisorFound = False
    for i in xrange(2, n):
        if n % i == 0:
            divisorFound = True
    return not divisorFound     # divisorFound is true if and only if
there is a number i (1<i<n) with n % i == 0

for i in range(2,20):
    if isPrime(i):
        print i, 'is a prime number'

By the way, do note that your cast to float is not a good idea. It
probably won't hurt you in this case, but it definitely won't improve
things. You'd much rather check exact equality with integers than with
floats.

-- 
André Engels, andreengels at gmail.com


More information about the Tutor mailing list