Write a program to check and display whether the number is Goldbach number or not using only for loop or while loop & java.util.* package
The output must be like below-
Enter a number:
6
Goldbach number
import java.util.*;
public class App {
/**
* The start point of the program
*
* @param args
*
*/
public static void main(String[] args) {
Scanner keyBoard = new Scanner(System.in);
System.out.println("Enter a number: ");
int number = keyBoard.nextInt();
boolean[] isPrime = new boolean[number];
for (int i = 2; i < number; i++)
isPrime[i] = true;
// determine primes < n using Sieve of Eratosthenes
for (int factor = 2; factor*factor < number; factor++) {
if (isPrime[factor]) {
for (int j = factor; factor*j < number; j++)
isPrime[factor*j] = false;
}
}
// count primes
int primes = 0;
for (int i = 2; i < number; i++)
if (isPrime[i]) primes++;
int[] numbers = new int[primes];
int count = 0;
for (int i = 0; i < number; i++)
if (isPrime[i]) numbers[count++] = i;
int left = 0, right = count-1;
while (left <= right) {
if (numbers[left] + numbers[right] == number) break;
else if (numbers[left] + numbers[right] < number) left++;
else right--;
}
if (numbers[left] + numbers[right] == number)
System.out.println("Goldbach number");
else
System.out.println("NOT Goldbach number");
keyBoard.close();
}
}
Comments
Leave a comment