0% found this document useful (0 votes)
30 views2 pages

Public Class: Checkprime

This Java code checks if a given number can be expressed as the sum of two prime numbers. It takes a number as input, loops through all possible combinations of two numbers from 2 to half the input, and checks if both are prime using a separate function. If a combination of two prime numbers summing to the input is found, it prints them out, and sets a flag. Otherwise, it prints that the number cannot be expressed as a sum of two primes.

Uploaded by

Abhishek__kr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views2 pages

Public Class: Checkprime

This Java code checks if a given number can be expressed as the sum of two prime numbers. It takes a number as input, loops through all possible combinations of two numbers from 2 to half the input, and checks if both are prime using a separate function. If a combination of two prime numbers summing to the input is found, it prints them out, and sets a flag. Otherwise, it prints that the number cannot be expressed as a sum of two primes.

Uploaded by

Abhishek__kr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

public class CheckPrime {

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;
}
}

You might also like