summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorCliff Click <cliffc@acm.org>2024-09-30 09:38:34 -0700
committerCliff Click <cliffc@acm.org>2024-10-06 08:56:22 -0700
commit873455183525da257cae1da28b2959c0c409cb09 (patch)
tree21b1920604ad6e5b97c208f627ce7c9dafb5e2ba
parent45ab4741a5ace18e77b027a2f7e318327c33d4b7 (diff)
downloadSimple-873455183525da257cae1da28b2959c0c409cb09.tar.gz
Simple-873455183525da257cae1da28b2959c0c409cb09.zip
Sieve of Eratosthenes
Really badly needs `i++` and a `for` loop
-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(
"""