You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
36 lines
1.2 KiB
36 lines
1.2 KiB
// Package diffsquares provides a utility for the determination of the
|
|
// difference between the square of sums and sum of squares on a given
|
|
// number range.
|
|
package diffsquares
|
|
|
|
// SquareOfSums returns the square of the sum of the range of natural
|
|
// numbers from 1 to the given value.
|
|
func SquareOfSums(n int) int {
|
|
s := n * (n + 1) / 2
|
|
return s * s
|
|
}
|
|
|
|
// SumOfSquares returns the sum of the squares of the range of natural
|
|
// numbers from 1 to the given value.
|
|
func SumOfSquares(n int) int {
|
|
return n * (n + 1) * (2*n + 1) / 6
|
|
|
|
}
|
|
|
|
// Difference returns the difference between the sum of squares and the
|
|
// square of sums for the range of natural number up to the given value.
|
|
func Difference(n int) int {
|
|
return SquareOfSums(n) - SumOfSquares(n)
|
|
}
|
|
|
|
// Iteration 2 benchmark:
|
|
//
|
|
// PASS
|
|
// BenchmarkSquareOfSums-12 2000000000 1.04 ns/op
|
|
// BenchmarkSumOfSquares-12 2000000000 1.89 ns/op
|
|
// BenchmarkDifference-12 1000000000 2.75 ns/op
|
|
//
|
|
// benchmark old ns/op new ns/op delta
|
|
// BenchmarkSquareOfSums-12 55.6 1.04 -98.13%
|
|
// BenchmarkSumOfSquares-12 63.4 1.89 -97.02%
|
|
// BenchmarkDifference-12 114 2.75 -97.59%
|