From 06a2cc352e683ebbee9cc9073418fee355deaf00 Mon Sep 17 00:00:00 2001 From: bakurits Date: Tue, 1 Oct 2019 16:10:41 +0400 Subject: [PATCH] finding prime numbers from 1 to n using eratosthenes sieve --- numerical/prime_finder.go | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 numerical/prime_finder.go diff --git a/numerical/prime_finder.go b/numerical/prime_finder.go new file mode 100644 index 0000000..013f060 --- /dev/null +++ b/numerical/prime_finder.go @@ -0,0 +1,25 @@ +package main + +// PrimesUpTo finds all prime numbers from 1 to upperBound +// It's implemented using eratosthenes sieve +// Works in O(upperBound) time and space +func PrimesUpTo(upperBound int) []int { + // lp array stores minimal prime divisor for every number from 2 to upperBound + var lp []int + lp = make([]int, upperBound+1) + + // primes array stores primes + var primes []int + + for i := 2; i <= upperBound; i++ { + if lp[i] == 0 { + lp[i] = i + primes = append(primes, i) + } + for j := 0; j < len(primes) && primes[j] <= lp[i] && i*primes[j] <= upperBound; j++ { + lp[i*primes[j]] = primes[j] + } + } + + return primes +}