Reputation: 29
def is_divisible(n, primes):
for i in range(1, len(primes)):
if n % primes[i] == 0:
return True
return False
primes = []
def find_primes(N):
for j in range(1, N):
if is_divisible(j, primes) == False:
primes.append(j)
return primes
print(find_primes(200))
It should tell if a number is prime. And just prints 1.
Upvotes: 0
Views: 106
Reputation: 3
Your return primes
line is inside the for loop, which means that it just check the first number (i.e. 1
), and returns the result of that single calculation.
Your program should instead return the primes after looking at all the number, not just at the first one.
Upvotes: 0
Reputation: 2726
I think your issue is the indentation of the return statement. Here's your code fixed up:
def is_divisible(n, primes):
for i in range(0, len(primes)):
if n % primes[i] == 0:
return True
return False
def find_primes(N):
primes = []
for j in range(2, N):
if is_divisible(j, primes) == False:
primes.append(j)
return primes
Also avoid globals if you don't have to. find_primes doesnt need to access a global primes list it can declare it locally. Also, notice the range in find_primes that starts at 2 since every number is divisible by 1. Also, indendation matters. In both functions you do not iterate over the entire loop before returning the output (in find_primes) or the default (in is_divisible)
Upvotes: 2
Reputation: 35
In addition to the remark above (your program should start from 2), you do not want to return until you've completed the 'for j in range((2),N): ' loop. That is, you need to dedent the 'return primes' statement.
Upvotes: 0
Reputation: 6181
The first number you add is 1, every number is divisible by one and therefore is_divisible(x,1)== True and no number other then 1 is appended to the primes list.
Upvotes: 1
Reputation: 103155
All numbers are divisible by 1. When your program checks if 1 is a prime it determines yes it is so it appends it to the array. Then, when it checks if the next number 2 is divisible by any of the existing primes it says yes, it is divisible by 1 therefore it is not a prime etc etc.
Upvotes: 1