Exercism: Go version of the 'Difference of Squares' exercise.
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

9 years ago
9 years ago
9 years ago
  1. // Package diffsquares provides a utility for the determination of the
  2. // difference between the square of sums and sum of squares on a given
  3. // number range.
  4. package diffsquares
  5. // SquareOfSums returns the square of the sum of the range of natural
  6. // numbers from 1 to the given value.
  7. func SquareOfSums(n int) int {
  8. s := n * (n + 1) / 2
  9. return s * s
  10. }
  11. // SumOfSquares returns the sum of the squares of the range of natural
  12. // numbers from 1 to the given value.
  13. func SumOfSquares(n int) int {
  14. return n * (n + 1) * (2*n + 1) / 6
  15. }
  16. // Difference returns the difference between the sum of squares and the
  17. // square of sums for the range of natural number up to the given value.
  18. func Difference(n int) int {
  19. return SquareOfSums(n) - SumOfSquares(n)
  20. }
  21. // Iteration 2 benchmark:
  22. //
  23. // PASS
  24. // BenchmarkSquareOfSums-12 2000000000 1.04 ns/op
  25. // BenchmarkSumOfSquares-12 2000000000 1.89 ns/op
  26. // BenchmarkDifference-12 1000000000 2.75 ns/op
  27. //
  28. // benchmark old ns/op new ns/op delta
  29. // BenchmarkSquareOfSums-12 55.6 1.04 -98.13%
  30. // BenchmarkSumOfSquares-12 63.4 1.89 -97.02%
  31. // BenchmarkDifference-12 114 2.75 -97.59%