解求素数
不过哪种方法,数越大越耗时,甚至导致goland崩溃。
为了减少计算,只将素数组作为取余因子
package main
import (
"fmt"
)
func main() {
primeArray := []int{2}
for num := 2; num <= 10000; num++ {
isPrime := true
for _, i := range primeArray {
if num%i == 0 {
isPrime = false
break
}
}
if isPrime {
primeArray = append(primeArray, num)
}
}
fmt.Println(primeArray)
}
筛选法:
package main
import (
"fmt"
"math"
)
func sieveOfEratosthenes(n int) []int {
isPrime := make([]bool, n+1)
for i := 2; i <= n; i++ {
isPrime[i] = true
}
for i := 2; i <= int(math.Sqrt(float64(n))); i++ {
if isPrime[i] {
for j := i * i; j <= n; j += i {
isPrime[j] = false
}
}
}
primes := []int{}
for i := 2; i <= n; i++ {
if isPrime[i] {
primes = append(primes, i)
}
}
return primes
}
func main() {
primes := sieveOfEratosthenes(1000000000)
for _, prime := range primes {
fmt.Println(prime)
}
}