Javatpoint Logo
Javatpoint Logo

Goldbach Number in Java

In this section, we will learn what is a Goldbach number and also create Java programs to check if the given number is Goldbach or not. The Goldbach number Java program frequently asked in Java coding tests to check the logic of the programmer.

In 1742, German mathematician Christian Goldbach proposed speculation that all prime numbers that are greater than 2 can be expressed as the sum of 2 odd prime numbers. It is speculation because there is no proof for the same.

Goldbach Number

A positive and even number is called a Goldbach number if the number can be expressed as the sum of two odd prime numbers. Note that all even integers greater than 4 are Goldbach numbers.

Goldbach Number Example

Consider the following numbers:

6 = 3 + 3

14 = 7 + 7 and 11 + 3

30 = 23 + 7, 11 + 19, and 13 + 17

28 = 11 + 17

12 = 7 + 5

10 = 5 + 5 and 7 + 3

We see that the numbers are positive and even, expressed as the sum of odd numbers.

Steps to Find Goldbach Number

  1. Read or initialize a number N.
  2. Store it in another variable.
  3. Check if the given number N is even or not.
  4. If the number is odd, print "Invalid input".
  5. If the number is even, follow the procedure given below:
    • Define two arrays one for storing the prime numbers and the other for calculating the prime number.
    • Find all prime numbers till the entered number using a for loop and store it in an array.
    • In the second array, store only odd prime numbers using if statement.
    • Display the odd prime pairs.
  6. By using the for loop, store the sum of two odd prime numbers in a variable (sum).
  7. Using the if statement, compare the sum with the original number N. If the sum is equal to the original number, the given number N is Goldbach Number, else not.

Let's implement the above steps in a Java program.

Goldbach Number Java Program

We will solve the problem using recursion. In the following program, we have defined a method isPrime() to check if the number is prime or not.

GoldbachNumberExample1.java

Output 1:

Goldbach Number in Java

Output 2:

Goldbach Number in Java

Output 3:

Goldbach Number in Java

Let's see another logic to find the Goldbach number.

GoldbachNumberExample2.java

Output 1:

Goldbach Number in Java

Output 2:

Goldbach Number in Java





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA