HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMajor

Project Euler #14 - Longest Collatz sequence

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
sequenceprojecteulerlongestcollatz

Problem

I'm attempting some Project Euler problems in an attempt to learn Python. While I can get the correct answer quite easily, my programs are quite slow. Project Euler, if doing it correctly, specifies that each program should run in <1 minute. Some of mine take 5-10 mins.

Here is one example.

x=1;
terms=0;
maxTerms=0;
maxTermsNum=0;
for x in range(1,1000000):
    i=x;
    while (i!=1):
        terms+=1;
        if (i%2==0):
            i/=2
        else:
            i=3*i+1
    if (terms>maxTerms):
        maxTerms=terms;
        maxTermsNum=x;
        print(x);
    terms=0;
print("Biggest one: is %s." %maxTermsNum)


It produces the correct answer, but it takes a long long time. How can I speed this up? This is also in 32-bit Windows.

Solution

While many of the Project Euler problems can be solved by brute force, this often isn't the fastest way to do them. Usually there is some kind of algorithmic insight that you can apply that will make your solution faster. This kind of insight is independent of programming language - simply running your code through a hypothetical "go-fast compiler" still won't match the speed of the correct algorithm.

In your case, here's a hint. Many of the sequences you calculate look the same as ones you've previously done. How could you use that information to speed up your algorithm?

Context

StackExchange Code Review Q#7505, answer score: 25

Revisions (0)

No revisions yet.