Saturday 15 December 2012

Sum of Prime Numbers

 #include <stdio.h>
 #include <math.h>
 int main(void)
 {
     unsigned int i,j,s=0,is_prime,sq;

     for(i=3;i<=1000;i++)  

//you can make the program for upperbound and lowerbound also.....
     {
         is_prime = 1; // Assuming that current value of i is prime
         sq=sqrt(i);
         // Checking for prime
         for(j=2;j<=sq;j++)
         {
             if(i%j==0) // Not prime, set is_prime to 0 and break
             {
                 is_prime = 0;
                 break;
             }
         }

         if(is_prime) // If the number is prime, sum it up
         {
             s += i;
             // optionally you can print the prime numbers too
             printf("%d ",i);
         }
     }

     printf("\n\nThe sum of the prime numbers = %d",s);
     return 0;
 }

2 comments:

  1. Why don't you optimize the isprime() function? i = 2 to i/2 is not needed.. check out prime number calculation algos.

    ReplyDelete
  2. awesome yr........

    ReplyDelete