Project Euler Problem 14 Segfault
I'm trying to solve this problem from Project Euler. Here's the problem.
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.
My code segfaults when it reaches item 113383. And i don't know what is wrong with it.
Any help or advice highly appreciated.
int f(int i);
long long terms; /* how many terms for each number */
long long i;
long long max = 0;
terms = terms = 0;
for(i = 2; i < 1000000; i++)
long long step = 0;
long long temp = i;
temp = f(temp);
while(temp > i - 1); /* all the values under i are already calculated */
terms[i] = step + terms[temp];
max = terms[i]>max?terms[i]:max;
int f(int n)
return (n%2 == 0) ? n/2 : 3*n+1;