Python Challenge - Prime Number Finder

def isPrime(n): for i in range(2,n): if n % i == 0: return False return True def prime_finder(n): numbers = list(range(2, n+1)) primes = [] for i in numbers: if isPrime(i): primes.append(i) return primes print(prime_finder(11))

Hey goran_021,

How does 2 get added to the primes list? Obviously 2 % 2 == 0 and 2 % 1 == 0. How do lines 3, 4 and 5 account for that?

I appreciate this isn’t specific to your code but I understood yours the most. Any help would be much appreciated.

Thanks

Hi.

See here :
for i in range(2,n):
if n % i == 0:

If we talk about num 2, then it’s range(2,2), and range from 2 to 2 is none. Because range goes from start(2) to end minus one(2 - 1), and that would be range from 2 to 1 which doesn’t exist so result is none instead of zero you would normally expect.

Take care:)

You are a legend, thank you so much!

1 Like

big code

def prime_finder(n): foo = [] def isComposite(n2): x = [True] for i in range(1, n2 + 1): if n2 % i == 0 and not(i == 1 or i == n2): x.append(False) return not(x[-1]) for i in range(1, n + 1): if not(isComposite(i)) and not(i == 1 or i == 0): foo.append(i) return foo for i2 in range(40): print("{} {}\n".format(i2, prime_finder(i2)))
def prime_finder(n): primes = [] for i in range(2,n+1): print(i) flag = False for x in range(2,i): if flag: continue if i % x == 0: flag = True if not flag: primes.append(i) return primes print(prime_finder(11))

Using list comprehension

def prime_finder(n):
num_list = [num for num in range(2, n+1) if num>1 if all(num % y != 0 for y in range(2, num))]
return num_list

print(prime_finder(11))

from math import factorial def prime_finder(n): # Write your code here primes = [] for nums in range(2, n+1): fact = factorial(nums-1)+1 if fact%nums == 0: primes.append(nums) return primes print(prime_finder(11))

here’s my solution using wilsons’s theorem :slight_smile:

1 Like
def prime_finder(n): # Write your code here def is_prime(m): for j in range(2,m): if m%j == 0: return False return True prime_list = [] for i in range(2, n+1): if is_prime(i): prime_list.append(i) return prime_list print(prime_finder(100))
def prime_finder(n): # Write your code here prime_n = [] for i in range(2,n+1): prime_test = [] for j in range(2,i+1): if i%j == 0: prime_test.append(j) if len(prime_test) == 1: prime_n.append(i) return prime_n print(prime_finder(11))