Day 74: Sum of Prime Numbers of 100DaysCodingChallenge

Hello all, 

#day74 

Day74 

Today's my task was to Write a Program to check if an integer (entered by the user)

can be expressed as the sum of two prime numbers,if yes then

print all possible combinations with the use of functions.


Example

Enter a positive integer: 34

OUTPUT:

34 = 3 + 31

34 = 5 + 29

34 = 11 + 23

34 = 17 + 17

I have started the 100 days of coding challenge to improve my programming skills..

Code : 

//#include <stdio.h>
let n = prompt("Enter a positive integer: ");
//checkPrime(n);
function isPrime(n){
  let  i, flag = 0;  
  //scanf("%d", &n);
  for (i = 2; i <= n / 2; ++i) {
    // condition for i to be a prime number
    if (checkPrime(i) == 1) {
      // condition for n-i to be a prime number
      if (checkPrime(n - i) == 1) {
        console.log(`${n} = ${i} + ${n - i}`);
        flag = 1;
      }
    }
  }

  if (flag == 0)
    console.log(`${n} cannot be expressed as the sum of two prime numbers. `);
  return 0;
}

// function to check prime number
function checkPrime(n) 
{
  let i, isPrime = 1;
  // 0 and 1 are not prime numbers
  if (n == 0 || n == 1) {
    isPrime = 0;
  }
  else {
    for(i = 2; i <= n/2; ++i) {
      if(n % i == 0) {
        isPrime = 0;
        break;
      }
    }
  }
  return isPrime;
}
isPrime(n);

Output :     

 



Happy Coding:)

Thank you...      

Comments

Popular posts from this blog

Day 55: Pattern using loops of 100DaysCodingChallenge

Day 7: Square or Power Integer Numbers of 100DaysCodingChallenge

Day 45: Pattern using loops of 100DaysCodingChallenge