Comparison of 'Sieve of Eratosthenes' and 'Sieve of Euler':
refer to:https://www.jianshu.com/p/7867517826e7
Sieve of Eratosthenes (埃氏篩選法):
func SieveOfEratosthenes(n int) int {
p := make([]int, 0)
flagNotPrime := make([]bool, n+1)
// Sieve of Eratosthenes
for i := 2; i <= n; i++ {
if !flagNotPrime[i] {
p = append(p, i)
for j := i*i; j <= n; j += i {
flagNotPrime[j] = true
}
}
}
return len(p)
}
Sieve of Euler(歐拉篩選法):
func SieveOfEuler(n int) int {
p := make([]int, 0)
flagNotPrime := make([]bool, n+1)
// Sieve of Eular
for i := 2; i <= n; i++ {
if !flagNotPrime[i] {
p = append(p, i)
}
for j := 0; j < len(p) && p[j] * i <= n; j++ {
flagNotPrime[i*p[j]] = true
if i % p[j] == 0 {
break
}
}
}
return len(p)
}
Here is the benchmarking routines:
package basic_1007_test
import (
"testing"
"pta/basic_1007"
)
func BenchmarkSieveOfEratosthenes(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
basic_1007.SieveOfEratosthenes(100000000)
}
}
func BenchmarkSieveOfEuler(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
basic_1007.SieveOfEuler(100000000)
}
}
Run the benchmarking:
(11:00 dabs@CNU1343VF8 basic_1007) > go test -v -run="none" -bench=. -benchtime="10s" -benchmem
goos: linux
goarch: amd64
pkg: pta/basic_1007
BenchmarkSieveOfEratosthenes
BenchmarkSieveOfEratosthenes-4 10 1048856325 ns/op 370910660 B/op 49 allocs/op
BenchmarkSieveOfEuler
BenchmarkSieveOfEuler-4 8 1379414530 ns/op 370910476 B/op 49 allocs/op
PASS
ok pta/basic_1007 23.970s
As we can see, SieveOfEuler is bit slower than SieveOfEratosthenes in golang.
From the OJ of PTA platform:
Run time is 7ms using SieveOfEuler and 5ms using SieveOfEratosthenes.