(first, I assume the tick on the end of your code is a typo in your stack overflow post, not the code itself)
Consider what happens when next_odd
is prime. This block:
while b<float(math.sqrt(next_odd)):
if next_odd%b>0:
b+=1
if next_odd%b == 0:
check+=1
will increment b
up until the square root of next_odd
without ever incrementing check
. That means that if check > 0:
won't pass, and thus count
never increments, and you then you just spin around in the
while count<=10:
, skipping both if
blocks because their conditions are false.
In other words, you don't actually say what to do when next_odd
is prime. This is also an example of why while
shouldn't really be used when all you want to do is increment through numbers (which is what you're using it for here). Try something like this:
max_num = 10000 # or whatever
for odd in range(3, max_num, 2):
factor_count = 0
for factor in range(2, math.floor(math.sqrt(max_num)) + 1):
if odd % factor == 0:
factor_count += 1
if factor_count == 0:
print(odd)
A couple points about this code:
- There's no (non-constant) variables in the global scope. That makes it much easier to reason about how the script's state changes over time.
- The use of for-loops over while-loops guarantees that our script won't get caught in an infinite loop due to an erroneous (or unaccounted for) condition.
- The use of for-loops means that we don't have to worry about incrementing all of the variables ourselves, which dramatically reduces the amount of state that we have to manage.
Hope that helps!
Oh, note that there are much more efficient ways to compute primes also. See https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes