Created
November 9, 2013 06:16
-
-
Save dlubarov/7382360 to your computer and use it in GitHub Desktop.
Enumerate the primes using only unary arithmetic
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
interface NaturalNumber {} | |
class Zero implements NaturalNumber { | |
@Override | |
public String toString() { | |
return "0"; | |
} | |
} | |
class Successor implements NaturalNumber { | |
final NaturalNumber prev; | |
Successor(NaturalNumber prev) { | |
this.prev = prev; | |
} | |
@Override | |
public String toString() { | |
return String.format("S(%s)", prev); | |
} | |
} | |
class Primes { | |
static boolean isGreater(NaturalNumber a, NaturalNumber b) { | |
while (a instanceof Successor && b instanceof Successor) { | |
a = ((Successor) a).prev; | |
b = ((Successor) b).prev; | |
} | |
return a instanceof Successor; | |
} | |
static NaturalNumber difference(NaturalNumber a, NaturalNumber b) { | |
if (isGreater(b, a)) | |
throw new IllegalArgumentException("Second operand was greater than first."); | |
while (b instanceof Successor) { | |
a = ((Successor) a).prev; | |
b = ((Successor) b).prev; | |
} | |
return a; | |
} | |
static NaturalNumber remainder(NaturalNumber a, NaturalNumber b) { | |
while (!isGreater(b, a)) | |
a = difference(a, b); | |
return a; | |
} | |
static boolean isDivisible(NaturalNumber a, NaturalNumber b) { | |
return remainder(a, b) instanceof Zero; | |
} | |
static boolean isPrime(NaturalNumber n) { | |
if (n instanceof Zero || ((Successor) n).prev instanceof Zero) | |
return false; | |
NaturalNumber d = new Successor(new Successor(new Zero())); | |
while (isGreater(n, d)) { | |
if (isDivisible(n, d)) | |
return false; | |
d = new Successor(d); | |
} | |
return true; | |
} | |
public static void main(String[] args) { | |
for (NaturalNumber n = new Zero();; n = new Successor(n)) | |
if (isPrime(n)) | |
System.out.println(n); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment