Browse Source

Refactor with mathematical formulas

master
jimi 9 years ago
parent
commit
290516606b
  1. 24
      difference_of_squares.go

24
difference_of_squares.go

@ -6,21 +6,14 @@ package diffsquares
// SquareOfSums returns the square of the sum of the range of natural // SquareOfSums returns the square of the sum of the range of natural
// numbers from 1 to the given value. // numbers from 1 to the given value.
func SquareOfSums(n int) int { func SquareOfSums(n int) int {
var s int
for i := 1; i <= n; i++ {
s += i
}
s := n * (n + 1) / 2
return s * s return s * s
} }
// SumOfSquares returns the sum of the squares of the range of natural // SumOfSquares returns the sum of the squares of the range of natural
// numbers from 1 to the given value. // numbers from 1 to the given value.
func SumOfSquares(n int) int { func SumOfSquares(n int) int {
var s int
for i := 1; i <= n; i++ {
s += i * i
}
return s
return n * (n + 1) * (2*n + 1) / 6
} }
@ -30,9 +23,14 @@ func Difference(n int) int {
return SquareOfSums(n) - SumOfSquares(n) return SquareOfSums(n) - SumOfSquares(n)
} }
// Iteration 1 benchmark:
// Iteration 2 benchmark:
// //
// PASS // PASS
// BenchmarkSquareOfSums-12 30000000 56.5 ns/op
// BenchmarkSumOfSquares-12 20000000 63.8 ns/op
// BenchmarkDifference-12 20000000 113 ns/op
// 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%
Loading…
Cancel
Save