Simple Primality Test

This is a feature demo for the blog with a simple example. It shows that the blog has support for compiling Go code to WASM and LaTeX rendering.

The lengths I will go to to not write javascript :,)

Setup

I needed to install TinyGo and Katex.

Katex was simple, it just required me adding it to templates/index.html. In order to serve the compiled WASM, use the base Makefile target. This will put the compiled WASM into the static/ assets. In order to load in the exported functions using load_wasm, I had to add this code. One gotcha is that the functions must be defined explicitly via //export <function_name>.

I also needed to add this to my config.toml:

katex_enable = true
katex_auto_render = true

[mediaTypes]
[mediaTypes."application/wasm"]
suffixes = ["wasm"]

Finally, I had to add wasm_exec.js to the static assets. Following this tutorial is a great place to start.

In order to see the pre-compiled Markdown, just look at this page's source code

Finding Primes

The canonical example for primality testing is the Sieve of Eratosthenes.

The algorithm works like so;

  • Starting at i = 2, mark every multiple of i up to some n as "seen".
  • Loop until $$ i > \sqrt{n} $$
  • The "unseen" values are primes

This algorithm has the time complexity

$$ O(n \cdot log \cdot log ( n )) $$

Expressed in Go, this is:

func findPrimes(n float64) []int {
	all := make([]bool, int(n))
	for i := 2; i < int(n); i++ {
		all[i] = true
	}

	nSqrt := int(math.Sqrt(n)) + 1

	for p := 2; p < nSqrt; p++ {
		if all[p] {
			j := p * p
			for j < int(n) {
				all[j] = false
				j += p
			}
		}
	}

	primes := []int{}
	for i, e := range all {
		if e {
			primes = append(primes, i)
		}
	}

	return primes
}

The code is also available here.

Demo