Check if a number is the sum of two primes

The problem is to check a random number n may be the sum of two random primes. For instance,

if n = 34, the possibilities can be (3 + 31), (5 + 29), (17 + 17) ...

So far, I managed to save the primes in the array, but I have no idea how I could check if n is the sum of two primes.

This is part of my code:

 public static void primeNumbers(int n) { int i = 0, candidate = 2, countArray = 0, countPrime = 0; boolean flag = true; while (candidate <= n) { flag = true; for (i = 2; i < candidate; i++) { if ((candidate % i) == 0) { flag = false; break; } } if (flag) { countPrime++; } candidate++; } int[] primeNumbers = new int[countPrime]; while (candidate <= n) { flag = true; for (i = 2; i < candidate; i++) { if ((candidate % i) == 0) { flag = false; break; } } if (flag) { primeNumbers[countArray] = candidate; } candidate++; countArray++; } for (i = 0; i <= primeNumbers.length; i++) { } } 

At first, I calculated how many primes are between 1-n, so I can declare and initialize my array for primes. Then I store the primes in an array. But now I have no idea how I could check if n sum of two prime numbers.

+5
source share
1 answer

Given that you already have a list of β€œprimes less than a given number,” it’s a very simple task to check if two primes can be summed with a given number.

 for(int i=0; i<array.length; i++){ int firstNum = array[i]; int secondNum = givenNum - firstNum; /* Now if it is possible to sum up two prime nums to result into given num, secondNum should also be prime and be inside array */ if(ArrayUtils.contains(array, secondNum)){ System.out.println("Yes, it is possible. Numbers are "+ firstNum + " and " + secondNum); } } 

EDIT: ArrayUtils is part of the Apache Commons Lang library. However, you can use ArrayList to use the contains method.

+2
source

Source: https://habr.com/ru/post/1275143/


All Articles