// Problem 41
// 11 April 2003
//
// We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.
//
// What is the largest n-digit pandigital prime that exists?
#include <iostream>
#include <windows.h>
#include <ctime>
using namespace std;
//************************************
// Method: IsPandigital
// FullName: IsPandigital
// Describe: 检查num是否为Pandigital
// Access: public
// Returns: bool
// Qualifier:
// Parameter: int num
//************************************
bool IsPandigital(int num, int n)
{
bool exsitDigit[9] = {false}; //位bit,用于记录存在的位
int currentDigit = 0;
while(num != 0)
{
currentDigit = num % 10;
if(currentDigit == 0) //含0,不符合要求
{
return false;
}
if(currentDigit > n) //数字大于当前位数,不符合要求
{
return false;
}
if(exsitDigit[currentDigit - 1]) //已存在这个数字
{
return false;
}
exsitDigit[currentDigit - 1] = true; //记录
num /= 10;
}
return true;
}
//************************************
// Method: IsPrimeNum
// FullName: IsPrimeNum
// Describe: 判断某数是否为素数
// Access: public
// Returns: bool
// Qualifier:
// Parameter: int num
//************************************
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;
}
//************************************
// Method: F1
// FullName: F1
// Describe: 这个算法比较糟糕,是最愚笨的遍历,十分耗时
// Access: public
// Returns: void
// Qualifier:
//************************************
void F1()
{
cout << "void F1()" << endl;
LARGE_INTEGER timeStart, timeEnd, freq;
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&timeStart);
const int MAX_NUM = 987654321; //最大的Pandigital
int numCount = 9; //当前数字的位数
int nextDecrease = 100000000; //下个位数改变点
int result = 0; //找到的结果
//从大到小遍历所有数
for(int i = MAX_NUM; i > 0; i -= 2)
{
//找到需要的数字
if(IsPandigital(i, numCount) && IsPrimeNum(i))
{
result = i;
break;
}
//位数改变
if(i < nextDecrease)
{
nextDecrease /= 10;
--numCount;
}
}
cout << "结果为:" << result << 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()
结果为:7652413
Total Milliseconds is 148553
By GodMoon
Wed Apr 11 12:58:45 2012
*/
【ProjectEuler】ProjectEuler_041
最新推荐文章于 2024-04-15 10:46:09 发布