Project Euler p#14

NOTE: Please don't post the correct answer.

Hi I am solving Problem 14 of project euler. http://projecteuler.net/problem=14.
I wrote a program for it and get the answer 910107. But the site says wrong answer. Can you tell me what am I doing wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>

using namespace std;

int main()
{
    int starting_num = 0; //Answer variable;
    int chain_length_p = 0; //Previous chain length
    int chain_length_c = 1; //Current chain length <-- increases in the loop
    int current_term = 0; //Current term
    
    for(int i = 14; i<1000000; i++)
    {
        current_term = i; //Set the current term to i;
        while(current_term > 1) //Continue looping and finding terms until its 1
        {
            if(current_term%2 == 0) 
            {
                current_term = current_term/2; //Use the this formula if current term is even
                chain_length_c++; //Increase chain length
            }
            else 
            {
                current_term = (3*current_term)+1; //Use this formula if current term is odd
                chain_length_c++; //Increase chain length
            }
        }
        if(chain_length_c > chain_length_p) //If current chain length is greater then the older one
        {
            chain_length_p = chain_length_c; //Set the older chain length to the newer
            starting_num = i; //Set the starting num to i
        }
        
        chain_length_c = 1; //Set current chain length to 1
    }
    
    cout << starting_num << " as starting num produces a chain of length: " << chain_length_p << endl; //Display result
    
    return 0;
}
Last edited on
your program finds the last longest chain number. The site perhaps asks for the first one.

nah I was wrong...

It seems that some number produces term > 2^32, which causes integer overflow. Change all integer variables to (unsigned) long long will prevent this.
1
2
3
4
long long starting_num = 0; //Answer variable;
long long chain_length_p = 0; //Previous chain length
long long chain_length_c = 1; //Current chain length <-- increases in the loop
long long current_term = 0; //Current term 
Last edited on
Ah thanks it worked ^_^.
Topic archived. No new replies allowed.