# Program to express a number as a sum of two prime numbers

12 May 2023

Write a program to express a number as a sum of two prime numbers ## Description about the Program to express a number as a sum of two prime numbers

Get a number as input from the user and express that number as sum of two prime numbers.

Input

4

Output

4 can be expressed as sum of 2 and 2

## C Program to express a number as a sum of two prime numbers

#include <stdio.h>

int sumprimes(int n)

{

int i, isPrime = 1;

for(i = 2; i <= n/2; ++i)

{

if(n % i == 0)

{

isPrime = 0;

break;

}

}

return isPrime;

}

int main()

{

int num, i;

printf("Insert the num: ");

scanf("%d", &num);

int flag = 0;

for(i = 2; i <= num/2; ++i)

{

if(sumprimes(i) == 1)

{

if(sumprimes(num-i) == 1)

{

printf("%d can be expressed as the sum of %d and %d", num, i,num-i);

flag = 1;

}

}

}

if(flag == 0)

printf("%d cannot be expressed as the sum of two primes", num);

return 0;

}

## C++ Program to express a number as a sum of two prime numbers

#include <iostream>

using namespace std;

int sumprimes(int n)

{

int i, isPrime = 1;

for(i = 2; i <= n/2; ++i)

{

if(n % i == 0)

{

isPrime = 0;

break;

}

}

return isPrime;

}

int main()

{

int num, i;

cout<<"Insert the num: ";

cin>>num;

int flag = 0;

for(i = 2; i <= num/2; ++i)

{

if(sumprimes(i) == 1)

{

if(sumprimes(num-i) == 1)

{

cout<<num<<" can be expressed as the sum of "<<i<<" and "<<num-i;

flag = 1;

}

}

}

if(flag == 0)

cout<<num<<" cannot be expressed as the sum of two primes";

return 0;

}

## Java Program to express a number as a sum of two prime numbers

import java.util.Scanner;

public class Main

{

static int sumprimes(int n)

{

int i, isPrime = 1;

for(i = 2; i <= n/2; ++i)

{

if(n % i == 0)

{

isPrime = 0;

break;

}

}

return isPrime;

}

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter a number : ");

int num = sc.nextInt();

int flag = 0;

for(int i = 2; i <= num/2; ++i)

{

if(sumprimes(i) == 1)

{

if(sumprimes(num-i) == 1)

{

System.out.println(num+" can be expressed as the sum of "+i+" and "+(num-i));

flag = 1;

}

}

}

if(flag == 0)

System.out.println(num+" cannot be expressed as the sum of two primes");

}

}

## Python Program to express a number as a sum of two prime numbers

num = int(input('Enter a number :'))

arr = []

for i in range(2,num):

flag = 0

for j in range(2,i):

if i % j == 0:

flag = 1

if flag == 0:

arr.append(i)

flag = 0

for i in range(len(arr)):

for j in range(i+1,len(arr)):

if(arr[i] + arr[j] == num):

flag = 1

print(str(num) + " can be expressed as the sum of " + str(arr[i]) + " and " + str(arr[j]))

break

if(flag == 0):

print('No Prime numbers can give sum of ' + str(num)) 