I have a school exercise where I have to make a Prime Number Generator and Optimize it later on. After I did some optimization my Generator started to also print the number "4" which is obviously not a prime number.
My Code looks like this:
import time
#Primzahlen errechnen
c = 0
print("Enter Upper Value:")
Max_wert = input()
x = int(Max_wert)
print("Prime Numbers between 0 and ", x, "are:")
time.sleep(1) # Pause für 2 Sekunden
for num in range(2, x):
num2 = int(num / 2)
for i in range(2, num2):
if (num % i) <= 0:
break
else:
print(num)
c+=1
print(c, "Prime Numbers were found")
When I remove the line: > num2 = int(num / 2)
and change num2
in the for loop back to num
then everything works fine.
The problem is that in the for loop you have to test from 2
to floor(sqrt(num))
not to num/2
(any further control is useless, check this out: Why do we check up to the square root of a prime number to determine if it is prime? ) and , most important, the range for i
has to be between range(2, num2 + 1)
and not range(2, num2)
The for loop code will be:
for num in range(2, x):
num2 = math.floor(math.sqrt(num))
for i in range(2, num2 + 1):
if (num % i) <= 0:
break
else:
print(num)
c+=1
An example output will be:
Enter Upper Value:
10
Prime Numbers between 0 and 10 are:
2
3
5
7
4 Prime Numbers were found
In the loop for i in range(2, num2):
when num is between 2 and 5 program flow will not enter the for loop.
So they 2,3,4,5 are just getting printed, not because they are prime or not prime.
Because num2=int(num/2), when num is in [2,5], for loop range is (2,1)(2,1)(2,2)(2,2).
when num=2,3 range(2,1) doesn't make sense as you are asking it to start at 2 and go till 1, so it exits for loop and goes directly to else block printing 2 AND 3.
when num=4,5 range(2,2) will not give anything as ur asking it to start at 2 and go till 2(not inclusive) so again it goes directly to else block printing 4 and 5.
For values of num, more than 5 ur code runs as it should.
So ur for loop should be:
for num in range(2, x):
num2 = int(num / 2 + 1)
for i in range(2, num2):
if (num % i) <= 0:
break
else:
print(num)
c+=1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.