## Eratosthenes - for AWK~Plus.
# 'CopyOnWriteArrayList'(不思議な Listです)の実装確認と、Groovy性能確認用です.
# This is for checking the implementation of'CopyOnWriteArrayList'(mysterious List) and
# Groovy performance confirmation.
# 'AtomicArray'は、パッチを当てないと、Groovyで'ArrayIndexOutOfBoundsException'エラーになる.
# If'AtomicArray 'is not patched, an error will occur.
@CompileStatic  # 型推論をクラスファイルに反映(ダイナミック言語としての柔軟さは、失われます)
BEGIN {
    val T = new AtomicArray()
    # val T = new AtomicMap()
    val start: double = systime()
    val maxarray: int = 10000
    val maxprime: int = int(ARGV[1])
    for (var base: int = 2; maxprime >= base; base += maxarray) {
        val arraysize: int = (maxarray < maxprime - base + 1) ? maxarray : maxprime - base + 1
        var k: int = 0
        delete T
        T[maxarray] = null	# patch for Groovy(OutOfBounds)
        for (var i: int = 2; (base + arraysize) / 2 > i; ++i) {
            if (base <= i)
                k = i * 2
            else if (base % i)
                k = int(base / i + 1) * i
            else
                k = base
            for (; base + arraysize > k; k += i)
                T[k - base] = "."
        }
        for (var i: int = 0; arraysize > i; ++i)
            if (!(i in T))
                print base + i
    }
    printf "%gsec.\n", systime() - start >"/dev/stderr"
}