ocaml: phase 5.1 sieve.ml baseline (Sieve of Eratosthenes)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 24s
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 24s
Counts primes <= 50, expected 15.
Stresses the recently-added Array module + the new array-indexing
syntax together with nested control flow:
let sieve = Array.make (n + 1) true in
sieve.(0) <- false;
sieve.(1) <- false;
for i = 2 to n do
if sieve.(i) then begin
let j = ref (i * i) in
while !j <= n do
sieve.(!j) <- false;
j := !j + i
done
end
done;
...
Exercises: Array.make, arr.(i), arr.(i) <- v, nested for/while,
begin..end blocks, ref/!/:=, integer arithmetic. 24 baseline
programs total.
This commit is contained in:
@@ -22,6 +22,7 @@
|
||||
"queens.ml": 2,
|
||||
"quicksort.ml": 44,
|
||||
"roman.ml": 44,
|
||||
"sieve.ml": 15,
|
||||
"sum_squares.ml": 385,
|
||||
"word_count.ml": 3
|
||||
}
|
||||
|
||||
22
lib/ocaml/baseline/sieve.ml
Normal file
22
lib/ocaml/baseline/sieve.ml
Normal file
@@ -0,0 +1,22 @@
|
||||
let count_primes n =
|
||||
let sieve = Array.make (n + 1) true in
|
||||
sieve.(0) <- false;
|
||||
sieve.(1) <- false;
|
||||
for i = 2 to n do
|
||||
if sieve.(i) then begin
|
||||
let j = ref (i * i) in
|
||||
while !j <= n do
|
||||
sieve.(!j) <- false;
|
||||
j := !j + i
|
||||
done
|
||||
end
|
||||
done;
|
||||
let count = ref 0 in
|
||||
for i = 2 to n do
|
||||
if sieve.(i) then count := !count + 1
|
||||
done;
|
||||
!count
|
||||
|
||||
;;
|
||||
|
||||
count_primes 50
|
||||
Reference in New Issue
Block a user