// 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()2337537331331737379731373797739397總和為748317Total Milliseconds is 453.591By GodMoonSat Nov 05 14:09:20 2011*/