免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1781 | 回复: 0
打印 上一主题 下一主题

[其他] Project Euler - 010 [复制链接]

论坛徽章:
4
白羊座
日期:2013-11-05 10:26:09冥斗士
日期:2015-11-17 14:19:55白银圣斗士
日期:2015-11-17 15:13:0815-16赛季CBA联赛之新疆
日期:2016-04-01 09:10:58
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2015-09-28 15:25 |只看该作者 |倒序浏览
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以内的所有素数之和。

代码:

  1. package main

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

  6. func IsPrime(number int) bool {
  7.         if number < 2 {
  8.                 return false
  9.         }

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

  12.         if number > 2 && number % 2 == 0 {
  13.                 isPrime = false
  14.         }

  15.         for test := 3; test < root + 1; test+=2 {
  16.                 if (number % test == 0){
  17.                         isPrime = false
  18.                         break
  19.                 }
  20.         }
  21.        
  22.         return isPrime
  23. }

  24. func BuildPrimeFactorTable(scope int) ([]int) {
  25.         result := make([]int, 0)
  26.         if scope < 2 {
  27.                 return result
  28.         }
  29.        
  30.         result = append(result, 2)
  31.         for number := 3; number < scope + 1; number += 2 {
  32.                 if IsPrime(number) {
  33.                         result = append(result, number)
  34.                 }
  35.         }
  36.        
  37.         return result
  38. }

  39. func Problem010(scope int) int {
  40.         var sum int = 0
  41.         // 1. filter primes below scope
  42.         primes := BuildPrimeFactorTable(scope)
  43.        
  44.         // 2. calculation sum against filtered primes
  45.         for _, element := range primes {
  46.                 sum += element
  47.         }

  48.         return sum
  49. }

  50. func main() {
  51.         fmt.Println("Problem 010 result: ", Problem010(2000000))
  52. }

复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP