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个素数是多少?

代码:

  1. package main

  2. import (
  3.         "fmt"
  4.         "math"
  5. )

  6. func VerifyPrimeWithExistingPrimeList(number int, primes []int) bool {
  7.         if number < 2 {
  8.                 return false
  9.         }

  10.         isPrime := true
  11.         root := int(math.Sqrt(float64(number)))

  12.         for _, factor := range primes {
  13.                 if factor > root {
  14.                         break
  15.                 }

  16.                 if (number % factor == 0){
  17.                         isPrime = false
  18.                         break
  19.                 }
  20.         }
  21.        
  22.         return isPrime
  23. }

  24. func BuildPrimeTable(count int) []int {
  25.         primes := make([]int, 1)
  26.         if count < 1 {
  27.                 return primes
  28.         }
  29.         primes[0] = 2
  30.        
  31.         base := 3
  32.         for check := 0; check < count - 1; check++ {
  33.                 for {
  34.                         if (VerifyPrimeWithExistingPrimeList(base, primes) == false) {
  35.                                 base += 2
  36.                                 continue
  37.                         } else {
  38.                                 break
  39.                         }
  40.                 }

  41.                 primes = append(primes, base)
  42.                 base += 2
  43.         }

  44.         return primes
  45. }

  46. func Problem007(turn int) int {
  47.         primes := BuildPrimeTable(turn)
  48.         return primes[len(primes) - 1]
  49. }

  50. func main() {
  51.         fmt.Println("Problem 007 result: ", Problem007(10001))
  52. }
复制代码





欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2