Even Number With Prime Sum

Misc AlgorithmsAlgorithmsData Structure

All even numbers from 4, can be expressed as a sum of two prime numbers. Sometimes a number can have more than one sum of the prime number combination.

For an example the number 10 = (5 + 5) and (7 + 3)

This algorithm will find all of the combinations of prime sums for a given number.  When one number x is prime, then only we will check whether (number - x) is prime or not, if yes, the sum of x and (number – x) represents the even number.

Input and Output

Input:
Even number: 70
Output:
Prime sums
70 = 3 + 67
70 = 11 + 59
70 = 17 + 53
70 = 23 + 47
70 = 29 + 41

Algorithm

dispPrimeSum(num)

Input − The even number.

Output: Display the number using the sum of some prime numbers.

Begin
   if num is odd, then
      exit
   for i := 3 to num/2, do
      if i is prime, then
         if (num - i) is prime, then
            display ‘’num = i + (num – i)”
   done
End

Example

#include<iostream>
using namespace std;

int isPrime(int number) {        //check whether number is prime or not
   int lim;
      lim = number/2;

   for(int i = 2; i<=lim; i++) {
      if(number % i == 0)
         return 0;            //The number is not prime
   }
   return 1;                 //The number is prime
}

void displayPrimeSum(int num) {
   string res;
   if(num%2 != 0) {         //when number is an odd number
      cout << "Invalid Number";
      exit(1);
   }

   for(int i = 3; i <= num/2; i++) {
      if(isPrime(i)) {         //if i is a prime number
         if(isPrime(num-i)) {  //num - i is also prime, then
            cout << num <<"= "<<i << " + "<<(num-i)<<endl;
         }
      }
   }
}

main() {
   int num;
   cout << "Enter an even number: "; cin >> num;
   displayPrimeSum(num);
}

Output

Enter an even number: 70
70 = 3 + 67
70 = 11 + 59
70 = 17 + 53
70 = 23 + 47
70 = 29 + 41
raja
Published on 12-Jul-2018 09:08:59
Advertisements