I'm doing project euler Q14.
Which starting number, under one million, produces the longest collatz chain?
I was very surprised to see someone who could get a result in 0.7sec. More surprised when I see it is merely a naive brute force solution.
I was skeptical as I spent so much time to optimize my python version, getting the runtime down to about a minute. So I ran the code myself... OP wasn't lying.
I translated the same code to Python, it failed to terminate after 5 minutes.
What gives?
C version : http://codepad.org/VD9QJDkt
#include <stdio.h>
#include <time.h>
int main(int argc, char **argv)
{
int longest = 0;
int terms = 0;
int i;
unsigned long j;
clock_t begin, end;
double time_spent;
begin = clock();
for (i = 1; i <= 1000000; i++)
{
j = i;
int this_terms = 1;
while (j != 1)
{
this_terms++;
if (this_terms > terms)
{
terms = this_terms;
longest = i;
}
if (j % 2 == 0)
{
j = j / 2;
}
else
{
j = 3 * j + 1;
}
}
}
printf("longest: %d (%d)\n", longest, terms);
end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("It took %f seconds\n", time_spent);
return 0;
}
Python version: http://codepad.org/ZloPyEcz
import time
def iterative_brute_force(n):
longest = 0
terms = 0
for i in range(1, n + 1):
j = i
this_terms = 1
while j != 1:
this_terms += 1
if this_terms > terms:
terms = this_terms
longest = i
if j % 2 == 0:
j = j / 2
else:
j = 3 * j + 1
return longest, terms
t0 = time.time()
print(iterative_brute_force(10 ** 6))
t1 = time.time()
total = t1-t0
print(total)