summaryrefslogtreecommitdiff
path: root/chapter15/src/test/java
diff options
context:
space:
mode:
Diffstat (limited to 'chapter15/src/test/java')
-rw-r--r--chapter15/src/test/java/com/seaofnodes/simple/Chapter15Test.java49
1 files changed, 49 insertions, 0 deletions
diff --git a/chapter15/src/test/java/com/seaofnodes/simple/Chapter15Test.java b/chapter15/src/test/java/com/seaofnodes/simple/Chapter15Test.java
index a3dd48d0..f08abed0 100644
--- a/chapter15/src/test/java/com/seaofnodes/simple/Chapter15Test.java
+++ b/chapter15/src/test/java/com/seaofnodes/simple/Chapter15Test.java
@@ -71,6 +71,55 @@ return ary[1] * 1000 + ary[3]; // 1 * 1000 + 6
}
@Test
+ public void sieveOEratosthenes() {
+ Parser parser = new Parser(
+"""
+int[] ary = new int[arg];
+int[] primes = new int[arg];
+int nprimes = 0;
+// Find primes
+int j=2;
+while( j*j < arg ) {
+ while( ary[j]==1 ) j = j + 1;
+ // j is now a prime
+ primes[nprimes] = j; nprimes = nprimes + 1;
+ // Mark out the rest non-primes
+ int i = j + j;
+ while( i < ary# ) {
+ ary[i] = 1;
+ i = i + j;
+ }
+ j = j + 1;
+}
+// Now just collect the remaining primes
+while( j < arg ) {
+ if( ary[j] == 0 ) {
+ primes[nprimes] = j; nprimes = nprimes + 1;
+ }
+ j = j + 1;
+}
+// Shrink the result array to size
+int[] rez = new int[nprimes];
+j = 0;
+while( j < nprimes ) {
+ rez[j] = primes[j];
+ j = j + 1;
+}
+
+return rez;
+""");
+ StopNode stop = parser.parse(false).iterate(true);
+ assertEquals("return []int;", stop.toString());
+ Evaluator.Obj obj = (Evaluator.Obj)Evaluator.evaluate(stop, 20);
+ assertEquals("[]int {\n # :int;\n [] :int;\n}",obj.struct().toString());
+ long nprimes = (Long)obj.fields()[0];
+ long[] primes = new long[]{2,3,5,7,11,13,17,19};
+ for( int i=0; i<nprimes; i++ )
+ assertEquals(primes[i],(long)(Long)obj.fields()[i+1]);
+ }
+
+
+ @Test
public void testBad0() {
Parser parser = new Parser(
"""