トップページに戻る    次のC++のサンプルへ    前のC++のサンプルへ

Problem41 素数の中で最大のn桁Pandigital数

問題

n桁Pandigitalであるとは, 1からnまでの数を各桁に1つずつ持つこととする.

例えば2143は4桁Pandigital数であり, かつ素数である.
n桁(この問題の定義では9桁以下)Pandigitalな素数の中で最大の数を答えよ.


ソース

#include <limits.h>
#include <string>
#include <stack>
#include <Windows.h>
#include <iostream>

void main()
{
    int MaxAnswer = INT_MIN;
    const std::string StrKouho = "123456789";
    std::stack<std::string> stk;

    for (int I = 0; I <= (int)StrKouho.size()- 1; I++) {
        stk.push(StrKouho.substr(I,1));
    }

    while(stk.empty() == false){
        std::string Popped = stk.top(); stk.pop();

        bool IsPandigital = true;
        for (int I = 1; I <= (int)Popped.size(); I++) {
            char wkCharArr[100];wsprintf(wkCharArr,"%d",I);
            if(Popped.find(wkCharArr) == std::string::npos){
                IsPandigital = false;
                break;
            }
        }

        bool IsSosuu = true;
        int wkParsed = atoi(Popped.c_str());
        if (IsPandigital) {
            for (int I = 2; I*I <= wkParsed; I++) {
                if (wkParsed % I == 0) {
                    IsSosuu = false;
                    break;
                }
            }
        }

        if (IsPandigital && IsSosuu) {
            if (MaxAnswer < wkParsed) {
                std::cout << Popped << std::endl;
                MaxAnswer = wkParsed;
            }
        }

        for (int I = 0; I <= (int)StrKouho.size()- 1; I++) {
            if(Popped.find(StrKouho.at(I)) == std::string::npos){
                std::string WillPush = Popped + StrKouho.at(I);
                stk.push(WillPush);
            }
        }
    }
}


実行結果

7652413


解説

2から平方根までの整数で試し割りを行い、素数かの判定を行ってます。