From 290516606b2d14d70b28460ffde53a1895656615 Mon Sep 17 00:00:00 2001 From: jimi Date: Thu, 10 Mar 2016 06:57:43 -0600 Subject: [PATCH] Refactor with mathematical formulas --- difference_of_squares.go | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/difference_of_squares.go b/difference_of_squares.go index e040cbb..ff2f02b 100644 --- a/difference_of_squares.go +++ b/difference_of_squares.go @@ -6,21 +6,14 @@ 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 { - var s int - for i := 1; i <= n; i++ { - s += i - } + 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 { - 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) } -// Iteration 1 benchmark: +// Iteration 2 benchmark: // // 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%