Saturday 6 April 2013

Sum of n prime numbers

/* compiler- Turbo c++ author- Mangilal Sarswat --------------------------------------------------------*/

/* A program to find out sum of prime numbers. Suppose that user enter n=5 then output must be 28 that is sum of 5 prime values 2+3+5+7+11. You can modify this program for limited range as sum of prime numbers that come between 100 to 1000 etc.*/

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<math.h>

long sum(int n)
{
long count=1, sum=2;
for(long i=3; ;i++)
{
int pass=0;
for(long j=2; j<=ceil(sqrt(i)); j++)
{
if(i%j==0)
{
pass=1;
break;
}
}
if(pass==1);
else
{
count++;
sum=sum+i;
}
if(count==n) break;
}
return sum;
}

void main()
{
 while(1)
 {
  clrscr();
  int n;
  printf("Enter number of prime values");
  scanf("%d",&n);
  printf("Total of starting %d prime values is %d",n,sum(n));
  getch();
  if(n==99) exit(1);
 }
}

 /*==========================6 April, 2013 2:00 PM==========================*/