【ProjectEuler】ProjectEuler_037

// 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
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值