0

A problem with a generator of prime numbers

def prime_numbers(number): number_list = [] for i in range(1, number+1): for x in range(2, i): if i % x != 0: number_list.append(i) return number_list print( prime_numbers(30) ) So, I wanna generate prime numbers but the code works incorrectly

9th Oct 2020, 6:52 AM
Андрей Пермяков
Андрей Пермяков - avatar
4 Respuestas
9th Oct 2020, 7:55 AM
Avinesh
Avinesh - avatar
+ 5
Or you can add 'all' for i in range(2, number+1): if all(i % x != 0 for x in range(2, i)): number_list.append(i)
9th Oct 2020, 9:44 AM
Julia Shabanova
Julia Shabanova - avatar
+ 4
just wanna add that, you don't have to loop from 1->n, you can loop from 1->n/2 bcz the largest number that can divide any number is its half, and i suggest that you create a function isPrime(num) so it will make it easier and more readable :)
9th Oct 2020, 10:08 AM
Anon Fox
Anon Fox - avatar
0
Oh OK, I understood you, thanks mate.
9th Oct 2020, 9:45 AM
Андрей Пермяков
Андрей Пермяков - avatar