- 论坛徽章:
- 4
|
Problem 006:
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 55^2 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
问题6:
前十个自然数的平方和:1^2 + 2^2 + ... + 10^2 = 385
前十个自然数的和的平方是:(1 + 2 + ... + 10) ^ 2 = 55^2 = 3025
所以两者之差是:3025-385=2640
现在,试求出前一百个自然数的和的平方与平方和的差。
代码:
- package main
- import (
- "fmt"
- )
- func SumOfArithmeticSequence(min, max, step int) int {
- return (min + max) * ((max - min + 1) / step) / 2
- }
- func SumOfSquareSequence(min, max int) int {
- result := 0
- for index := min; index <= max; index++ {
- result = result + index * index
- }
- return result
- }
- func Problem006(maxNumber int) int {
- square := SumOfSquareSequence(1, maxNumber)
- sequence := SumOfArithmeticSequence(1, maxNumber, 1)
- return sequence * sequence - square
- }
- func main() {
- fmt.Println("Problem 006 result: ", Problem006(100))
- }
复制代码 |
|