Wednesday, November 26, 2008

Problem #45

This one took me a little bit. The first thing that should be realized is that every hexagonal number is a triangle number. Thus theres no need to check to make sure it is a hex if it is already a tri. Also, with the code I have, I start out with i being 144, because we already know that H(143) is what works, so we need one slightly larger than that to find the next number. My code runs to completion in 0.078 seconds.


#include <iostream>
#include <ctime>
#include <string>
#include <cmath>

//#define T(x) x * (x + 1) / 2
//#define iT(x) (sqrt(static_cast<double>(8 * x + 1)) - 1) / 2

//#define P(x) x * (3 * x - 1) / 2
#define iP(x) (sqrt(static_cast<double>(24 * x + 1)) + 1) / 6

#define H(x) x * (2 * x - 1)
//#define iH(x) (sqrt(static_cast<double>(8 * x + 1)) + 1) / 4

using namespace std;

bool findDeciaml (string);

int main()
{
clock_t start = clock();
long long int total = 0;
char buffer[256];
string str;
long long int holder = 0;

for (long long int i = 143 + 1; ;i++)
{
holder = H(i);

sprintf (buffer, "%f", iP(holder));
str = buffer;
if (!findDeciaml (str))
{
total = holder;
break;
}
}

cout << total << endl
<< "Process took " << (static_cast<double> (clock()) - start) / CLOCKS_PER_SEC << " seconds." << endl;

system("pause");
return 0;
}

bool findDeciaml (string str)
{
bool found = false;
for (int i = 0; i < str.size (); i++)
{
if (found == false)
{
if (str[i] == '.')
found = true;
}
else
if (str[i] - '0' > 0)
return true;
}
return false;
}

No comments: