Jadoo And Primes

Jadoo recently got to know what a prime number is. He got intrigued by this so much that he decided to find out the sum of the first N prime numbers (too curious!!). Help Jadoo solve this problem in the least time

Example:

Input:  n = 10
Output: 129

Approach

C++

#include <bits/stdc++.h>
using namespace std;

bool prime[100000001];
void primeInitialize()
{

    memset(primetruesizeof(prime));
    prime[0] = false;
    prime[1] = false;
    for (long long i = 2i * i <= 100000000i++)
    {
        if (prime[i])
        {
            for (long long j = i * ij <= 100000000j += i)
                prime[j] = false;
        }
    }
}

long long primes(long long n)
{

    long long ans = 0cnt = 0;
    for (long long i = 2;; i++)
    {
        if (prime[i])
        {
            ans += i;
            cnt++;
        }
        if (cnt == n)
            break;
    }
    return ans;
}
int main()
{

    long long n = 10;

    primeInitialize();

    cout << primes(n<< "\n";

    return 0;
}


No comments:

Post a Comment