zoukankan      html  css  js  c++  java
  • Project Euler Problem 118 Pandigital prime sets

    Pandigital prime sets

    Problem 118

    Using all of the digits 1 through 9 and concatenating them freely to form decimal integers, different sets can be formed. Interestingly with the set {2,5,47,89,631}, all of the elements belonging to it are prime.

    How many distinct sets containing each of the digits one through nine exactly once contain only prime elements?


    C++:

    #include <iostream>
    #include <algorithm>
    #include <cmath>
    
    using namespace std;
    
    const int N = 9;
    
    int val[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    long ans;
    
    bool isprime(long n)
    {
        if(n == 1)
            return false;
    
        if(n == 2)
            return true;
    
        if(n % 2 == 0)
            return false;
    
        long end = sqrt(n);
        for(long i=3; i<=end; i+=2)
            if(n % i == 0)
                return false;
    
        return true;
    }
    
    void primeset(int pos, long long leftval)
    {
        if(pos >= N) {
            ans++;
            return;
        }
    
        long long value = 0;
        while(pos < N) {
            value *= 10;
            value += val[pos++];
    
            if(isprime(value) && value >= leftval)
                primeset(pos, value);
        }
    }
    
    int main()
    {
        ans = 0;
        for(;;) {
            primeset(0, 0);
    
            if(!next_permutation(val, val + N))
                break;
        }
    
        cout << ans << endl;
    
        return 0;
    }



  • 相关阅读:
    js日期 操作
    c# 调用c++ dll
    多维数组与交错数组的转换
    c++多态
    c++ 指向类成员函数的函数指针
    c++虚析构函数的使用及其注意点
    c++模板实现 linq
    Php 常用类
    Php ORM 对象关系映射
    Php OpenID
  • 原文地址:https://www.cnblogs.com/tigerisland/p/7563990.html
Copyright © 2011-2022 走看看