Friday, November 28, 2008

Problem #47

2.203 seconds for it to complete on my computer. I had the loop check to 2 * sqrt(num), for checking for factors, because it didnt work correctly checking to just sqrt(num). Probably because something can be 2 * , so I tried to check all the way up to that, and the answer was correct.


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

using namespace std;

int countPrimeFactors (int);
bool isPrime (int);

int main()
{
clock_t start = clock();
int total = 0;

for (int i = 1; ; i++)
if (countPrimeFactors (i) == 4)
if (countPrimeFactors (i + 1) == 4)
if (countPrimeFactors (i + 2) == 4)
if (countPrimeFactors (i + 3) == 4)
{
total = i;
break;
}
cout << total << endl
<< "Process took " << (static_cast<double> (clock()) - start) / CLOCKS_PER_SEC << " seconds." << endl;

system("pause");
return 0;
}

int countPrimeFactors (int num)
{
int holder = 0;

for (int i = 1; i <= sqrt (static_cast<double> (num)) * 2; i++)
if (num % i == 0)
if (isPrime (i))
holder++;
return holder;
}

bool isPrime (int num)
{
if (num <= 1)
return false;

if (num == 2 || num == 3)
return true;

for (unsigned int i = 2; i < static_cast<int> (sqrt (static_cast<double> (num))) + 1; i++)
if (num % i == 0)
return false;
return true;
}

No comments: