Hello everyone! I´ve just started covering some python essentials, though I could not wait to tackle some of the coding challenges. There are surely better and more straightforward ways of tacking the challenge, but who knows… Maybe someone chose the same path as me and so this could be helpful.
I made my solution only checking with prime’s numbers (not all other numbers) & only check odd numbers, this must be faster than other aproachs.
My solution, using the Eratosthenes algorithm.
[codebyte] [/python3] type or paste code here def prime_finder(n): primes = [True] * (n + 1) primes = primes = False for num in range(2, int(n**0.5) + 1): if primes[num] == True: for multiple in range(num * num, n + 1, num): primes[multiple] = False prime_numbers = [num for num, is_prime in enumerate(primes) if is_prime == True] return prime_numbers print(prime_finder(11))
The original poster’s basically saying that the default is that the number isn’t a prime. Hence, p = False. Now, if the original number is divided by some number and the remainder after division is zero, it automatically means the original number is not a prime: so p = True. In Python:
if num % y == 0: p = True
I believe that the OP could make p = True as default. and then ask:
if p: list_of_primes.append(num)
for num in range(n+1):
if num > 1:
for i in range(2, num):
if (num % i) ==0:
def prime_finder(n): i=2 primes= while i<=n: no_primes= for j in range(2,i): if i%j==0: no_primes.append(i) if len(no_primes)==0: primes.append(i) i+=1 return primes print(prime_finder(51))
I used a lambda function to solve this challenge. The reason for using
num**0.5 (square root of the number) is for optimization. If a number doesn’t have a divisor smaller than its square root, then it won’t have any divisors larger than its square root either.
My solution is definitely inefficient and inelegant, but I’m happy I got it done quickly