Computer Science, asked by aspsingh6789, 3 months ago

program to find first 50 prime numbers sum and difference between sum of even number and sum of prim number​

Answers

Answered by Abhishek466430
0

Explanation:

Program to find sum of prime numbers between 1 to n

Write a program to find sum of all prime numbers between 1 to n.

Examples:

Input : 10

Output : 17

Explanation : Primes between 1 to 10 : 2, 3, 5, 7.

Input : 11

Output : 28

Explanation : Primes between 1 to 11 : 2, 3, 5, 7, 11.

Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.

A simple solution is to traverse all numbers from 1 to n. For every number, check if it is a prime. If yes, add it to result.

An efficient solution is to use Sieve of Eratosthenes to find all prime numbers from till n and then do their sum.

// C++ program to find sum of primes in

// range from 1 to n.

#include <bits/stdc++.h>

using namespace std;

// Returns sum of primes in range from

// 1 to n.

int sumOfPrimes(int n)

{

// Array to store prime numbers

bool prime[n + 1];

// Create a boolean array "prime[0..n]"

// and initialize all entries it as true.

// A value in prime[i] will finally be

// false if i is Not a prime, else true.

memset(prime, true, n + 1);

for (int p = 2; p * p <= n; p++) {

// If prime[p] is not changed, then

// it is a prime

if (prime[p] == true) {

// Update all multiples of p

for (int i = p * 2; i <= n; i += p)

prime[i] = false;

}

}

// Return sum of primes generated through

// Sieve.

int sum = 0;

for (int i = 2; i <= n; i++)

if (prime[i])

sum += i;

return sum;

}

// Driver code

int main()

{

int n = 11;

cout << sumOfPrimes(n);

return 0;

}

Similar questions