Python 3.3 vs. MSDOS Basic

John Immarino johimm at gmail.com
Mon Feb 18 20:13:04 CET 2013


I coded a Python solution for Problem #14 on the Project Euler website. I was very surprised to find that it took 107 sec. to run even though it's a pretty simple program.  I also coded an equivalent solution for the problem in the old MSDOS basic. (That's the 16 bit app of 1980s vintage.)  It ran in 56 sec. Is there a flaw in my coding, or is Python really this slow in this particular application. MSDOS Basic usually runs at a snails pace compared to Python.

Below is the problem and the code:



The following iterative sequence is defined for the set of positive integers:

n → n/2 (n is even)
n → 3n + 1 (n is odd)

Using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1

It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.

Which starting number, under one million, produces the longest chain?

NOTE: Once the chain starts the terms are allowed to go above one million.


max=0
m=0
while m<=1000000:
    m+=1
    count=0
    n=m
    while n!=1:
        count+=1
        if n%2==0:
            n=n//2
        else:
            n=3*n+1
    if count>max:
         max=count
         num=m
print(num,max)






More information about the Python-list mailing list