Monday 18 February 2019

Goldbach Number ISC 2018

Question: A Goldbach number is a positive even integer that can be expressed as the sum of two odd primes.
Note: All even integer numbers greater than 4 are Goldbach numbers.
Example:
6 = 3 + 3
10 = 3 + 7
10 = 5 + 5
Hence, 6 has one odd prime pair 3 and 3. Similarly, 10 has two odd prime pairs, i.e. 3, 7 and 5, 5.
Write a program to accept an even integer ‘N’ where N > 9 and N < 50. Find all the odd prime pairs whose sum is equal to the number ‘N’.
Test your program with the following data and some random data:
Example 1:
INPUT:
N = 14
OUTPUT:
Prime pairs are:
3, 11
7, 7
Example 2:
INPUT:
N = 30
OUTPUT:
Prime numbers are:
7, 23
11, 19
13, 17
Example 3:
INPUT:
N = 17
OUTPUT:
Invalid input. Number is odd.
Example 4:
INPUT:
N = 126
OUTPUT:
Invalid input. Number is out of range.





Solution:-


 import java.util.*;//Vivekkumarchandra.blogspot.com
class Goldbach{
    public static void main(String args[])

    {
        int n = 0;
        int p = 3;
        int q = 0;
        Scanner sc = new Scanner(System.in);
        System.out.print("N = ");
        n = sc.nextInt();
        if(n % 2 != 0){
            System.out.println("Invalid input. Number is odd.");
            return;
        }
        else if(n < 10 || n > 49){
            System.out.println("Invalid input. Number is out of range.");
            return;
        }
        System.out.println("Prime pairs are:");
        while(p < n){
            q = n - p;
            if(isPrime(p) && isPrime(q) && p <= q)
                System.out.println(p + ", " + q);
            p += 2;
        }
    }
    isPrime(int n){
        int f = 0;
        for(int i = 1; i <= n; i++){
            if(n % i == 0)
                f++;
        }
        if(f == 2)
            return true;
        return false;
    }
}



Output:-
N = 14
Prime pairs are:
3, 11
7, 7



N = 30
Prime numbers are:
7, 23
11, 19
13, 17

7 comments:

  1. Replies
    1. Please Can you Tell What Error message Did you Recieved?

      Delete
    2. Check that File name you created and class name are same..

      Delete
  2. Replies
    1. Please read the question carefully, here N > 9 and N < 50. So this program will show Number out of range.
      You can modify this limit by changing else if condition.

      Delete
  3. Replies
    1. Please make sure you have given same name to class (case sensitive)
      Save your file and close it and open it agen then try to compile it.

      Delete

Goldbach Number ISC 2018

Question: A Goldbach number is a positive even integer that can be expressed as the sum of two odd primes. Note: All even integer numbers ...