| 1 |
(module |
| 2 |
;; add the $even_check function to the top of the module |
| 3 |
(func $even_check (param $n i32) (result i32) |
| 4 |
local.get $n |
| 5 |
i32.const 2 |
| 6 |
i32.rem_u ;; if you take the remainder of a division by 2 |
| 7 |
i32.const 0 ;; even numbers will have a remainder 0 |
| 8 |
i32.eq ;; $n % 2 == 0 |
| 9 |
) |
| 10 |
;; add the $eq_2 function after $even_check |
| 11 |
(func $eq_2 (param $n i32) (result i32) |
| 12 |
local.get $n |
| 13 |
i32.const 2 |
| 14 |
i32.eq ;; returns 1 if $n == 2 |
| 15 |
) |
| 16 |
|
| 17 |
;; add $multiple_check after $eq_2 |
| 18 |
(func $multiple_check (param $n i32) (param $m i32) (result i32) |
| 19 |
local.get $n |
| 20 |
local.get $m |
| 21 |
i32.rem_u ;; get the remainder of $n / $m |
| 22 |
i32.const 0 ;; I want to know if the remainder is 0 |
| 23 |
i32.eq ;; that will tell us if $n is a multiple of $m |
| 24 |
) |
| 25 |
|
| 26 |
;; add the is_prime exported function after $multiple_check |
| 27 |
(func (export "is_prime") (param $n i32) (result i32) |
| 28 |
(local $i i32) |
| 29 |
(if (i32.eq (local.get $n) (i32.const 1)) ;; 1 is not prime |
| 30 |
(then |
| 31 |
i32.const 0 |
| 32 |
return |
| 33 |
)) |
| 34 |
(if (call $eq_2 (local.get $n)) ;; check to see if $n is 2 |
| 35 |
(then |
| 36 |
i32.const 1 ;; 2 is prime |
| 37 |
return |
| 38 |
) |
| 39 |
) |
| 40 |
(block $not_prime |
| 41 |
(call $even_check (local.get $n)) |
| 42 |
br_if $not_prime ;; even numbers are not prime (except 2) |
| 43 |
|
| 44 |
(local.set $i (i32.const 1)) |
| 45 |
(loop $prime_test_loop |
| 46 |
|
| 47 |
(local.tee $i (i32.add (local.get $i) (i32.const 2) ) ) ;; $i += 2 |
| 48 |
local.get $n ;; stack = [$n, $i] |
| 49 |
|
| 50 |
i32.ge_u ;; $i >= $n |
| 51 |
if ;; if $i >= $n, $n is prime |
| 52 |
i32.const 1 |
| 53 |
return |
| 54 |
end |
| 55 |
(call $multiple_check (local.get $n) (local.get $i)) |
| 56 |
br_if $not_prime ;; if $n is a multiple of $i this is not prime |
| 57 |
br $prime_test_loop ;; branch back to top of loop |
| 58 |
) ;; end of $prime_test_loop loop |
| 59 |
) ;; end of $not_prime block |
| 60 |
|
| 61 |
i32.const 0 ;; return false |
| 62 |
) |
| 63 |
) ;; end of module |
| 64 |
|
| 65 |
;; From https://github.com/battlelinegames/ArtOfWasm/blob/main/Chapter3/is_prime.wat |
| 66 |
|