Find the sum of all primes till N.
Example 1:
Input: n=10 Output: 17 // i.e 2+3+5+7
Approach:
Java
public class SummationofPrimes {
public static void main(String[] args) {
int n = 10;
System.out.println(summationPrimes(n));
}
//function to find the sum
//of primes of all number till n
private static int summationPrimes(int n) {
boolean prime[] = new boolean[1001];
prime[0] = false;
prime[1] = false;
for (int i = 2; i * i <= 1000; i++) {
if (!prime[i]) {
for (int j = i * i; j <= 1000; j += i)
prime[j] = true;
}
}
int sum[] = new int[1001];
for (int i = 2; i <= 1000; i++) {
if (!prime[i])
sum[i] = sum[i - 1] + i;
else
sum[i] = sum[i - 1];
}
return sum[n];
}
}
C++
#include <bits/stdc++.h>
using namespace std;
//function to find the sum
//of primes of all number till n
int summationPrimes(int n)
{
bool prime[1001];
memset(prime,true,sizeof(prime));
prime[0]=false;
prime[1]=false;
for(int i=2;i*i<=1000;i++)
{
if(prime[i])
{
for(int j=i*i;j<=1000;j+=i)
prime[j]=false;
}
}
int sum[1001]={0};
for(int i=2;i<=1000;i++)
{
if(prime[i])
sum[i]=sum[i-1]+i;
else
sum[i]=sum[i-1];
}
return sum[n];
}
int main()
{
int n=10;
cout<<summationPrimes(n);
return 0;
}
No comments:
Post a Comment