【ProjectEuler】ProjectEuler_037

來源:互聯網
上載者:User
// 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*/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.