- 論壇徽章:
- 4
|
本帖最后由 icymirror 于 2015-09-26 17:34 編輯
最近沒有那么忙,開始學(xué)習(xí)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以內(nèi)的3或5的倍數(shù)列出來,我們會得到:3, 5, 6和9。這些數(shù)之和是23。
現(xiàn)在,找出1000以內(nèi)的3或5的倍數(shù)的數(shù)字之和。
method 1- package 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))
- }
復(fù)制代碼 |
|