- 论坛徽章:
- 4
|
Problem 010:
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
问题10:
10以内的素数之和是:2 + 3 + 5 + 7 = 17。
试求2000000以内的所有素数之和。
代码:
- package main
- import (
- "fmt"
- "math"
- )
- func IsPrime(number int) bool {
- if number < 2 {
- return false
- }
- isPrime := true
- root := int(math.Sqrt(float64(number)))
- if number > 2 && number % 2 == 0 {
- isPrime = false
- }
- for test := 3; test < root + 1; test+=2 {
- if (number % test == 0){
- isPrime = false
- break
- }
- }
-
- return isPrime
- }
- func BuildPrimeFactorTable(scope int) ([]int) {
- result := make([]int, 0)
- if scope < 2 {
- return result
- }
-
- result = append(result, 2)
- for number := 3; number < scope + 1; number += 2 {
- if IsPrime(number) {
- result = append(result, number)
- }
- }
-
- return result
- }
- func Problem010(scope int) int {
- var sum int = 0
- // 1. filter primes below scope
- primes := BuildPrimeFactorTable(scope)
-
- // 2. calculation sum against filtered primes
- for _, element := range primes {
- sum += element
- }
- return sum
- }
- func main() {
- fmt.Println("Problem 010 result: ", Problem010(2000000))
- }
复制代码 |
|