Monday, 24 October 2016

Create a function sum_alt_primes(n) such that it sums every alternate prime number till 'n'

/*
Create a function sum_alt_primes(n) such that it sums every alternate prime number till 'n'.

Eg. sum_alt_primes(10) = 7
2 3 5 7
2 + 5 = 7 

Eg. sum_alt_primes(20) = 35
2 3 5 7 11 13 17 19
2 + 5 + 11 + 17 = 35
*/

#include<stdio.h>
int sum_alt_primes(int n) {

 // Variable Declaration
 int i,j,k, count=0,flag,sum=0;

 // Check all numbers from 2 to 'n' to find out prime number.
 for(i=2; i<=n; i++) {
 
  // Initialize a flag to zero
  flag = 0;
 
  // Check a number from above loop whether it is prime number or not.
  for(j=2; j<i; j++) {
  
   // Check whether a number is divisible or not by any other number.
   if(i%j == 0) {
    // Set flag value to ONE
    flag = 1;
    // Break the execution of current loop because the number is not prime
    break;
   }
  }
  // check flag value for prime check
  if(flag == 0) {
   // Increase the counter as we found one prime number
   count++;  
   // Check for alternate prime number
   if(count%2 != 0) {
    // Add the alternate prime number
    sum = sum + i;
   }
  }
 }
 // return the sum of the alternate prime number
 return sum;
}

int main() {
 int n;
 printf("Enter N:");
 scanf("%d", &n);
 printf("\nResult: %d", sum_alt_primes(n));
 return 0;
}

No comments: