I am working on projecteuler # 14, http://projecteuler.net/problem=14 and my code takes too long to run. Any tips, or hints for a beginner?
Code:
////////////////////////
/// ProjectEuler # 14///
////////////////////////
#include <iostream>
#include <tuple> //New, shaky on tuple
using namespace std;
bool tester(int n) //Even number tester//It works 100%
{
bool result = false;
if (n%2 == 0) result = true;
return result;
}
int collatz_counter (int collatz_number) //Collatz sequence counter//It works 100%
{
int j = collatz_number;
int total = 0;
do
{
if (tester(j))
{
j /=2;
total ++;
}
else
{
j = 3*j +1;
total ++;
}
}while (j!=1);
total +=1; // To account for the original number itself
return total;
}
pair <int n, int m> value_finder (int n)
{
int max = 0;
int max_number = 0;
for (int i = n; i>1; i--)
{
if(collatz_counter(i) > max)
{
max_number = i;
max = collatz_counter(i);
}
}
max_number++;
return{max, max_number};
}
int main (void)
{
int starter;
int x;
cout<<"Enter value :"<<endl;
cin>>starter;
cout<<endl;
int Max = 0;
int Max_Number = 0;
for (x = starter; x>= starter/2 ; x--)
{
int m, n;
tie(m, n) = value_finder(x);
if ( m> Max)
{
Max_Number = n;
Max = m;
}
}
cout<<" The maximum numbers in the collatz sequence is "<<m<<endl;
cout<<" The starting number of the collatz sequence is "<<n<<endl;
system ("pause");
return 0;
}