Algorithm
- Start with a given integer
num
that you want to check. - Create a function
isPrime(n)
to check if a given numbern
is prime. This function should returntrue
ifn
is prime andfalse
otherwise. - Iterate through all possible pairs of numbers
(i, j)
wherei
andj
are less thannum
. - For each pair
(i, j)
, check if bothi
andj
are prime numbers using theisPrime
function. - If both
i
andj
are prime, check if their sum is equal to the givennum
. - If the sum is equal to
num
, thennum
can be expressed as the sum of two prime numbers. - If no such pair is found after iterating through all possible pairs, conclude that
num
cannot be expressed as the sum of two prime numbers.
Code Examples
#1 Code Example- Represent a number as Sum of Two Prime Numbers
Code -
Java Programming
public class Main {
public static void main(String[] args) {
int number = 34;
boolean flag = false;
for (int i = 2; i < = number / 2; ++i) {
// condition for i to be a prime number
if (checkPrime(i)) {
// condition for n-i to be a prime number
if (checkPrime(number - i)) {
// n = primeNumber1 + primeNumber2
System.out.printf("%d = %d + %d\n", number, i, number - i);
flag = true;
}
}
}
if (!flag)
System.out.println(number + " cannot be expressed as the sum of two prime numbers.");
}
// Function to check prime number
static boolean checkPrime(int num) {
boolean isPrime = true;
for (int i = 2; i < = num / 2; ++i) {
if (num % i == 0) {
isPrime = false;
break;
}
}
return isPrime;
}
}
Copy The Code &
Try With Live Editor
Output
34 = 3 + 31
34 = 5 + 29
34 = 11 + 23
34 = 17 + 17
34 = 5 + 29
34 = 11 + 23
34 = 17 + 17
Demonstration
Java Programing Example to Check Whether a Number can be Expressed as Sum of Two Prime Numbers-DevsEnv