I can't seem to figure out why this is an infinite loop in python??
for i in range(n):
j=1
while((i*j)<n):
j+=1
shouldn't the outer loop go n times. incrementing j until its equal to n div i each time?
I can't seem to figure out why this is an infinite loop in python??
for i in range(n):
j=1
while((i*j)<n):
j+=1
shouldn't the outer loop go n times. incrementing j until its equal to n div i each time?
i
starts at 0
, so the while
condition stays always true; see the range docs for details.
You can create a "trace" showing the state changes of the variables.
etc.
You can prove that your trace is correct by inserting print
statements.
When in doubt, print it out.
i
starts at zero, so the condition for the inner loop is always 0*j < n
, which will always be true.
The first value in i
will be 0. 0 times anything is 0.
range(n)
starts at 0
, not 1
. 0 * j
will always be less than n
.
On the first time through the outer loop, the inner loop becomes an infinite loop. It doesn't matter what happens after that. There's no "after infinity".
i is 0 rewrite you loop like
for i in range(1,n):
j=1
while((i*j)<n):
j+=1
using this version of the range function will create a range that starts at 1 instead of 0