Trying to create a list of prime numbers in a fixed range. This is producing none sensical list but the code makes sense to my very naive and new-to-python brain. All help appreciated!
for number in range(2,100,2):
k = 1
while k*k < number:
k = 2
if number % k == 0:
break
else:
print(number)
CodePudding user response:
there are several bugs in your code. first, you don't check its divisibility by even numbers, any even number to be exact (including 2)! if it is meant as an optimization approach, make it more generic by not checking the numbers who are known already not to be prime. its called the sieve of eratosthenes another, is that you don't check the divisibility if n is a square root of a prime number as you pass the k*k = number case. this is my implementation for a naive n * sqrt(n):
for number in range(2,100):
prime, divisor = True, 2
while prime and divisor ** 2 <= number:
if number % divisor == 0:
prime = False
divisor = 1
if (prime):
print(number)
CodePudding user response:
Change like this:
for number in range(2, 101):
for k in range(2, number):
if (number % k) == 0:
break
else:
print(number)
CodePudding user response:
for number in range(1,100):
counter=0
for test in range(1,number 1):
if number%test==0:
counter=counter 1
if counter<=2:
print(number)