http://projecteuler.net/problem=41 1からnまですべてを各位に持つ数(1234, 4231, 987654321, etc)のうち、最大の素数を求める。 prev_permutationででかい順にブン回す。 {{{#!highlight c++ #include #include #include using namespace std; typedef long long ll; ll to_l(const string &s) { istringstream is(s); ll n; is >> n; return n; } bool isPrime(ll n) { for (ll i = 2; i * i <= n; i++) { if (n % i == 0) { return false; } } return true; } int main() { for (int i = 9; i >= 1; i--) { string s = ""; for (int j = i; j >= 1; j--) { s.push_back(j + '0'); } do { ll n = to_l(s); if (isPrime(n)) { cout << n << endl; return 0; } } while (prev_permutation(s.begin(), s.end())); } return 0; } }}}