
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Sum of Prime Numbers Between 1 to N in C++
In this problem, we are given a number n. Our task is to create a program to find sum of prime numbers between 1 to n in C++.
Prime Numbers are those numbers that have only two factors. They are the number and 1.
Let’s take an example to understand the problem
Input
n = 15
Output
41
Explanation
Prime numbers between 1 to 15 are 2, 3, 5, 7, 11, 13. The sum is 41.
Solution Approach
A simple way to solve the problem is by using a loop and checking if each number is a prime number or not and add all those which are prime.
To check if a number i is a prime number. We will loop from i to i/2. check if there lies a number that can divide i. If yes, then the number is not a prime number.
Program to illustrate the working of our solution
Example
#include <iostream> using namespace std; bool isPrime(int n){ for(int i = 2; i < n/2; i++){ if(n%i == 0){ return false; } } return true; } int findPrimeSum(int n){ int sumVal = 0; for(float i = 2; i <= n; i++){ if(isPrime(i)) sumVal += i; } return sumVal; } int main(){ int n = 15; cout<<"The sum of prime number between 1 to "<<n<<" is "<<findPrimeSum(n); return 0; }
Output
The sum of prime number between 1 to 15 is 45
An Effective solution is using Sieve of Eratosthenes to find prime numbers and adding them to find the required sum.
Program to illustrate the working of our solution
Example
#include <iostream> using namespace std; int findPrimeSum(int n){ int arr[n+1] = {0}; for (int i = 2; i < n; i++) { for (int j = i * i; j < n; j+=i) { arr[j - 1] = 1; } } int sumVal; for (int i = 2; i < n; i++) { if (arr[i - 1] == 0) sumVal += i; } return sumVal; } int main(){ int n = 15; cout<<"The sum of prime number between 1 to "<<n<<" is "<<findPrimeSum(n); return 0; }
Output
The sum of prime number between 1 to 15 is 41