Pythonme123
Pythonme123

Reputation: 3

Python primes function giving incorrect output

I have been asked to create two functions, the first is_divisible(n,primes) to check if a number is divisible by any other numbers in prime

and then the second which would use the first to find all the prime numbers in a particular range.

I don't know why, but i cannot work out how to get the primes to show. Anything obvious about what I am doing wrong?

def is_divisible(n, primes):    
    for p in primes:
        if n % p == 0:
            return True
        else:
            return False        

def find_primes(N):  
    primes=[]
    for n in range(2, N+1):
        is_divisible(n,primes)
        if False:
            primes.append(n)
    print(primes)

find_primes(20)

Upvotes: 0

Views: 154

Answers (3)

Lucas Ribeiro
Lucas Ribeiro

Reputation: 6292

This code is wrong:

    is_divisible(n,primes)
    if False:
        primes.append(n)

You should check if the divisibility inside the if condition. Try this:

    if not is_divisible(n,primes):
        primes.append(n)

Python evaluates 0 to False, and all numbers otherwise. So, it's not necessary to do something like "if condition == True". Use just if condition.

Upvotes: 0

nio
nio

Reputation: 5289

This if statement will never be true:

   if False:
       primes.append(n)

Rewrite the code like this:

  if is_divisible(n,primes)==False:
       primes.append(n)

Upvotes: 0

Steve Barnes
Steve Barnes

Reputation: 28415

def is_divisible(n, primes):    
    for p in primes:
        if n % p == 0:
            return True
    return False  # Only return False if no matches      

def find_primes(N):  
    primes=[]
    for n in range(2, N+1):
        if not is_divisible(n,primes)
            primes.append(n)
    print(primes)

print find_primes(20)

Upvotes: 1

Related Questions