Program opened below. You can scroll through the algorithm, Java code and output.

Goldbach Number

Download .java

Question

A Goldbach number is an even integer greater than 4 that can be expressed as the sum of two odd primes. Accept an even number and list all prime pairs whose sum is the number.

Step 1: Start. Step 2: Declare the variables and data structures required for the task. Step 3: Input N. Step 4: Validate the input values and display an error message if they are outside the permitted range. Step 5: Initialize the counters, flags, accumulators or result structures needed by the solution. Step 6: Check that N is even and greater than 4. Step 7: For each odd integer p from 3 to N/2, test whether p and N-p are prime. Step 8: If both are prime, display the pair. Step 9: Store the computed result and prepare it for display. Step 10: If no pair is found, display an appropriate message. Step 11: Stop.
Java
import java.util.*;
class GoldbachNumber {
    static boolean prime(int n) {
        if (n < 2) {
            return false;
        }
    for (int i = 2; i * i <= n; i++) {
        if (n % i == 0) {
            return false;
        }
}
return true;
}
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    if (n <= 4 || n % 2 != 0) {
        System.out.println("INVALID INPUT");
        return;
    }
boolean found = false;
for (int p = 3; p <= n / 2; p += 2) {
    if (prime(p) && prime(n - p)) {
    }
System.out.println(p + " + " + (n - p));
found = true;
}
if (!found) {
    System.out.println("NO PRIME PAIR FOUND");
}
}
}
Input: 10 Output: 3 + 7 5 + 5
← Previous Program 83 of 84 Next →

Share a comment or request a program

Use this form to send a comment, report an issue, or suggest a new practical. Your message will be saved for review by the school.