【ProjectEuler】ProjectEuler_037

2616 단어 nullIntegereach
// Problem 37
// 14 February 2003
//
// The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.
//
// Find the sum of the only eleven primes that are both truncatable from left to right and right to left.
//
// NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.

#include <iostream>
#include <windows.h>
#include <cmath>
#include <ctime>
using namespace std;

//  
bool IsPrimeNum(int num)
{
    if((num % 2 == 0 && num > 2) || num <= 1)
    {
        return false;
    }

    int sqrtNum = (int)sqrt((double)num);

    for(int i = 3; i <= sqrtNum; i += 2)
    {
        if(num % i == 0)
        {
            return false;
        }
    }

    return true;
}

//  Truncatable 
bool CheckTruncatableNum(const int num)
{
    int currentNum = num;

    // , , 
    while(currentNum != 0)
    {
        if(!IsPrimeNum(currentNum))
        {
            return false;
        }

        currentNum /= 10;
    }

    // 
    int tenDigit = 10;
    currentNum = num % tenDigit;

    while(currentNum != num)
    {
        if(!IsPrimeNum(currentNum))
        {
            return false;
        }

        tenDigit *= 10;
        currentNum = num % tenDigit;
    }

    return true;
}

void F1()
{
    cout << "void F1()" << endl;

    LARGE_INTEGER timeStart, timeEnd, freq;
    QueryPerformanceFrequency(&freq);
    QueryPerformanceCounter(&timeStart);

    const int MIN_NUM = 11;			// 11 , 2,3,5,7
    const int MAX_COUNT = 11;		// 11 
    int sum = 0;					// 
    int count = 0;					// 

    for(int i = MIN_NUM; count < MAX_COUNT; i += 2)
    {
        if(CheckTruncatableNum(i))
        {
            cout << i << endl;
            count++;
            sum += i;
        }
    }

    cout << " " << sum << endl;

    QueryPerformanceCounter(&timeEnd);
    cout << "Total Milliseconds is " << (double)(timeEnd.QuadPart - timeStart.QuadPart) * 1000 / freq.QuadPart << endl;

    time_t currentTime = time(NULL);
    char timeStr[30];
    ctime_s(timeStr, 30, ¤tTime);
    cout << endl << "By GodMoon" << endl << timeStr;
}

// 
int main()
{
    F1();
    return 0;
}

/*
void F1()
23
37
53
73
313
317
373
797
3137
3797
739397
 748317
Total Milliseconds is 453.591

By GodMoon
Sat Nov 05 14:09:20 2011
*/

좋은 웹페이지 즐겨찾기