The Program in C++ to Compute Sum of Prime numbers is given below:
#include <iostream>
using namespace std;
bool isPrime(int n) {
// check if n is a prime number
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0) return false;
}
return true;
}
int main() {
int n, count = 0, sum = 0;
cout<<"Hello Codeauri Family,Enter the value of an n:\n";
cin>>n;
for (int i = 2; count < n; i++) {
if (isPrime(i)) {
sum += i;
count++;
}
}
cout << "The sum of the first " << n << " prime numbers is: " << sum << endl;
return 0;
}
Output:
Hello Codeauri Family,Enter the value of an n:
9
The sum of the first 9 prime numbers is: 100
Pro-Tips💡
This program first defines a function isPrime()
that takes an integer as input and returns a Boolean value indicating whether the input is a prime number or not.
The main()
function then prompts the user to enter the number of prime numbers to add, and uses a for loop to iterate from 2 to the user-specified number.
For each number, the program checks if it is a prime number using the isPrime()
function.
If it is prime, the program adds it to the sum and increments a count variable.
Once the count reaches the user-specified number, the program outputs the sum of the prime numbers.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.