Project Euler #77: Prime summations

Sort by

recency

|

13 Discussions

|

  • + 0 comments

    python

    # Enter your code here. Read input from STDIN. Print output to STDOUT
    import math
    
    def check(n):
        for i in range(2, int(math.sqrt(n))+1):
            if n%i == 0:
                return False
        return True
    
    p = []
    a = [0]*1001
    for i in range(2, 1001):
        if a[i] == 0:
            if check(i):
                p.append(i)
                for j in range(2*i, 1001, i):
                    a[j] = 1
    
    n = [0]*1001
    n[0] = 1
    for n1 in p:
        for i in range(n1, 1001):
            n[i] += n[i-n1]
    
    t = int(input())
    while t > 0:
        m = int(input())
        print(n[m])
        t -= 1
    
  • + 0 comments

    Wrong answer for Test case 3. All others are correct. What could it be?

    UPDATE: I found the answer, the error was in small dimesion of the array. Now 100 % is done.

  • + 0 comments

    You should learn by heart 2 classic algorithms: Coin Change algorithm and Sieve Primes algorithm

  • + 0 comments

    Took me a bit of time to get the implementation of the loops right. Really have to brush up on my dynamic programming skills.

  • + 0 comments
    bool check(int n)
    {
        for(int i=2;i<=sqrt(n);i++)
            if(n%i==0)
                return 0;
        return 1;
    }
    int main() 
    {
        vector <int> p;
        int a[1001]={0};
        for(int i=2;i<=1000;i++)
        {
            if(a[i]==0){
            if(check(i)==1)
            {
                p.push_back(i);
                for(int j=2*i;j<=1000;j=j+i)
                    a[j]=1;
            }
            }
        }
       
        vector<int>n(1001);
        n[0]=1;
        for(auto &n1 : p)
        {
            for(int i=n1;i<=1000;i++)
                n[i]+=n[i-n1];
        }
        int t;
        cin >> t;
        while(t--)
        {
            int m;
            cin >> m;
            cout << n[m]<<endl;
        }
    }