-
-
Save m4scosta/935f91e558c37e129464af2b947d159d to your computer and use it in GitHub Desktop.
Goldbach's conjecture - http://en.wikipedia.org/wiki/Goldbach%27s_conjecture
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Demonstrates the Goldbach's conjecture - Every even integer greater than 2 can be expressed as the sum of two primes | |
* | |
* author: Igor Hercowitz | |
* | |
* usage: java Goldbach <number> | |
* output: the sum of the primes list | |
* | |
* ex: | |
* > java Goldbach 100 | |
* 100 can be writen as: [97+3, 89+11, 83+17, 71+29, 59+41, 53+47] | |
* | |
* | |
*/ | |
import java.lang.Math; | |
import java.util.List; | |
import java.util.ArrayList; | |
import java.util.Collections; | |
public class Goldbach { | |
public boolean is_prime(int n) { | |
if ( (n % 2) == 0) return false; | |
double squarert = Math.abs(Math.sqrt(n))+1; | |
for (int i=3; i < squarert; i+=2) { | |
if ( (n % i) == 0) return false; | |
} | |
return true; | |
} | |
public static void main(String[] args) { | |
int value = Integer.parseInt(args[0]); | |
Goldbach g = new Goldbach(); | |
List<Integer> primes = new ArrayList<Integer>(); | |
for (int i=3; i < value; i+=2) { | |
if (g.is_prime(i)) { | |
primes.add(i); | |
} | |
} | |
Collections.reverse(primes); | |
List<String> expressions = new ArrayList<String>(); | |
while (primes.size() > 0) { | |
int x = primes.remove(0); | |
int y = value - x; | |
if (primes.indexOf(y) != -1) { | |
primes.remove(primes.indexOf(y)); | |
expressions.add(x+"+"+y); | |
} | |
} | |
System.out.println(value+" can be writen as: " + expressions); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment