Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class TwoPrimes {
- public static void main(String[] args) {
- int N = 10000000;
- boolean[] isprime = new boolean[N];
- for (int i = 2; i < N; i++)
- isprime[i] = true;
- // determine primes < N using Sieve of Eratosthenes
- for (int i = 2; i * i < N; i++) {
- if (isprime[i]) {
- for (int j = i; i * j < N; j++)
- isprime[i * j] = false;
- }
- }
- // count primes
- int primes = 0;
- for (int i = 2; i < N; i++)
- if (isprime[i])
- primes++;
- // store primes in list
- int[] list = new int[primes];
- int n = 0;
- for (int i = 0; i < N; i++)
- if (isprime[i])
- list[n++] = i;
- // check if N can be expressed as sum of two primes
- for (int i = 4; i <= 10000000; i += 2) {
- int currNum = i;
- int left = 0, right = list.length - 1;
- while (left <= right && right > 0) {
- if (list[left] + list[right] == currNum)
- break;
- else if (list[left] + list[right] < currNum)
- left++;
- else
- right--;
- }
- if (list[left] + list[right] == currNum)
- System.out.println(currNum + " = " + list[left] + " + "
- + list[right]);
- else
- System.out.println(currNum
- + " not expressible as sum of two primes");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement