From cfb18dec7503c73b7ab87f97b0c8f02a3d1bccfd Mon Sep 17 00:00:00 2001 From: "Peter J. Holzer" Date: Tue, 13 Jul 2021 11:17:37 +0200 Subject: [PATCH] Avoid overflow --- eratosthenes_parallel.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/eratosthenes_parallel.go b/eratosthenes_parallel.go index 517e34a..0489826 100644 --- a/eratosthenes_parallel.go +++ b/eratosthenes_parallel.go @@ -36,8 +36,16 @@ func main() { p := nCpus var jnext int64 + // XXX - i * i can overflow. + // bail out before that happens + if n / i < i { + continue; + } for j := i * i; j < n; j = jnext { jnext = ((n-j)/(2*i)/p+1)*(2*i) + j + if jnext > n { + jnext = n + } markGroup.Add(1) go markMultiples(sieve, i, j, jnext) p--