Hi All,
Hope you don't mind me asking this here. I'm new to C++ having learnt Python and BASIC years ago at school I figured it was time to learn a 'real' programming language.
I've been working my way through the Euler problems, but problem 14 is stumping me... The problem (
http://projecteuler.net/problem=14) is Collatz' Problem, which should (I thought) be fairly simple to solve using an iterative method.
I have googled and googled, but haven't found anyone else with a similar problem with me. I am 95% sure that the problem doesn't involve integer overloads or similar (but I am using long long int just incase).
I know this is probably not the quickest of methods, and if I was going to speed I would have used a dynamic method, storing solutions as I went.
So here is my code:
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 41 42 43 44 45
|
#include <iostream>
using namespace std;
long long int noIts(long long int n)
{
/* This itterative function returns the number of iterations to get to n = 1.
The only variable which we are working with is n, the current number in the Collatz
Sequence.
The function returns the number of iterations which it takes n to get to n = 1
*/
if (n == 1)
//Have we reached the end of the sequence?
return 1;
if (n % 2 == 0)
//If n is even
return (noIts(n/2) + 1);
else
//If n is odd
return (noIts(3*n + 1) + 1);
}
int main()
{
//the maximum number which we will loop to
long int const maxStart = 1e6;
//to store the number with the most iterations so far
long int iMax = -1;
//loop through all numbers bellow maxStart
for (long int i = 1; i <= maxStart; i++)
{
if (iMax < noIts(i))
iMax = i;
}
//display the final solution
cout << iMax << endl;
return 0;
}
|
Now this code keeps giving me the solution 35655 (after about a second of working), which apparently uses 324 iterations to get to 0, but the Euler website keeps telling me I'm wrong.
I have spent a long time looking over this, making small changes, and trying to debug, but I can't find where I have gone wrong.
If anyone can give me a hint as to where I should be looking, it would be very much appreciated!
Cheers
Adam
PS. If it helps, I am using Ubuntu 11.10, gpp to compile, and Code::Blocks to write