I would like it if someone could please explain to me why the following code has so much additional overhead. At 100k iterations, the speed is the same for either case (2.2 sec). When increasing to 1E6 iterations case "B" never finishes, while case "A" takes only 29 seconds.
Case "A"
while n is not 1:
foo
Case "B"
while n > 1:
foo
Complete code if of any help
def coll(n):
count = 0
# while n is not 1:
while n > 1:
count += 1
if not n % 2:
n /= 2
else:
n = 3*n + 1
return count
for x in range(1,100000):
count = coll(x)
First of all, you should use n > 1
or n != 1
, not n is not 1
. The fact that the latter works is an implementation detail, and obviously it's not working for you.
The reason it's not working is because there are values of x
in your code that cause the Collatz sequence to go over the value of sys.maxint
, which turns n
into a long
. Then, even when it ends up going back down to 1
, it's actually 1L
; a long
, not an int
.
Try using while n is not 1 and repr(n) != '1L':
, and it'll work as you expect. But don't do that; just use n > 1
or n != 1
.