Wednesday, November 26, 2008

Problem #43

I was kind of lazy with this, but finally got around to re-creating my code for it. Here it is, it runs in 4.187 seconds on my computer.


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

using namespace std;

bool isCompatible (string);
bool checkDivisibility (int, int, int, int);

int main()
{
clock_t start = clock();
long long int total = 0;
long long int holder = 0;
string str;

int num[]={0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

sort (num, num + 10);

do {
str.clear ();
for (int i = 0; i < 10; i++)
str += num[i] + '0';
if (isCompatible (str))
{
holder = 0;
for (int i = 0; i < 10; i++)
holder += (str[str.size () - 1 - i] - '0') * pow (10, static_cast<double>(i));
total += holder;
}
} while ( next_permutation (num, num + 10));


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

system("pause");
return 0;
}

bool isCompatible (string str)
{
if ((str[3] - '0') % 2 == 0)
if (((str[2] - '0') + (str[3] - '0') + (str[4] - '0')) % 3 == 0)
if ((str[5] - '0') % 5 == 0)
if (checkDivisibility (str[4] - '0', str[5] - '0', str[6] - '0', 7))
if (checkDivisibility (str[5] - '0', str[6] - '0', str[7] - '0', 11))
if (checkDivisibility (str[6] - '0', str[7] - '0', str[8] - '0', 13))
if (checkDivisibility (str[7] - '0', str[8] - '0', str[9] - '0', 17))
return true;
else
return false;
else
return false;
else
return false;
else
return false;
else
return false;
else
return false;
else
return false;
}

bool checkDivisibility (int a, int b, int c, int d)
{
if ((a * 100 + b * 10 + c) % d == 0)
return true;
return false;
}

No comments: