From 873455183525da257cae1da28b2959c0c409cb09 Mon Sep 17 00:00:00 2001 From: Cliff Click Date: Mon, 30 Sep 2024 09:38:34 -0700 Subject: Sieve of Eratosthenes Really badly needs `i++` and a `for` loop --- .../java/com/seaofnodes/simple/Chapter15Test.java | 49 ++++++++++++++++++++++ 1 file changed, 49 insertions(+) (limited to 'chapter15/src') 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 @@ -70,6 +70,55 @@ return ary[1] * 1000 + ary[3]; // 1 * 1000 + 6 assertEquals(1006L, Evaluator.evaluate(stop, 4)); } + @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