icymirror 发表于 2015-09-24 23:05

Project Euler - 001

本帖最后由 icymirror 于 2015-09-26 17:34 编辑

最近没有那么忙,开始学习golang,有空就拿Project Euler上的题目来练手吧。

Problem 1.
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.

问题1:
如果我们把10以内的3或5的倍数列出来,我们会得到:3, 5, 6和9。这些数之和是23。
现在,找出1000以内的3或5的倍数的数字之和。

method 1package main

import (
        "fmt"
)

func Problem001_basic(scope, factor1, factor2 int) int {
        sum := 0

        for index := 0; index <= scope; index += factor1 {
                sum = sum + index
        }
       
        for index := 0; index <= scope; index += factor2 {
                sum = sum + index
        }
       
        for index := 0; index <= scope; index += factor1 * factor2 {
                sum = sum - index
        }
       
        return sum
}

func Problem001_improve(scope, factor1, factor2 int) int {
        sum := (factor1 + scope / factor1 * factor1) * (scope / factor1) / 2
        sum = sum + (factor2 + scope / factor2 * factor2) * (scope / factor2) / 2
        factor3 := factor1 * factor2
        sum = sum -(factor3 + scope / factor3 * factor3) * (scope / factor3) / 2
        return sum
}

func main() {
        fmt.Println("Problem 001 result: ", Problem001_basic(1000, 3, 5))
        fmt.Println("Problem 001 result: ", Problem001_improve(1000, 3, 5))
}

ba_du_co 发表于 2015-10-09 14:42

本帖最后由 ba_du_co 于 2015-10-09 14:45 编辑

拿来练练手。
233168#!perl6
say [+] (^1000).grep: * %% (3|5);

zsszss0000 发表于 2016-04-21 15:45

结果是 234168吧!回复 2# ba_du_co


   
页: [1]
查看完整版本: Project Euler - 001