Chinaunix
标题:
Project Euler - 007
[打印本页]
作者:
icymirror
时间:
2015-09-27 12:46
标题:
Project Euler - 007
Problem 007:
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
问题7:
通过列出前6个素数:2, 3, 5, 7, 11, 13, 我们可以发现第六个素数是13.
那么,第10001个素数是多少?
代码:
package main
import (
"fmt"
"math"
)
func VerifyPrimeWithExistingPrimeList(number int, primes []int) bool {
if number < 2 {
return false
}
isPrime := true
root := int(math.Sqrt(float64(number)))
for _, factor := range primes {
if factor > root {
break
}
if (number % factor == 0){
isPrime = false
break
}
}
return isPrime
}
func BuildPrimeTable(count int) []int {
primes := make([]int, 1)
if count < 1 {
return primes
}
primes[0] = 2
base := 3
for check := 0; check < count - 1; check++ {
for {
if (VerifyPrimeWithExistingPrimeList(base, primes) == false) {
base += 2
continue
} else {
break
}
}
primes = append(primes, base)
base += 2
}
return primes
}
func Problem007(turn int) int {
primes := BuildPrimeTable(turn)
return primes[len(primes) - 1]
}
func main() {
fmt.Println("Problem 007 result: ", Problem007(10001))
}
复制代码
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2