Skip to content

Commit

Permalink
Add sumsqrdiff solution, unit test and benchmark
Browse files Browse the repository at this point in the history
  • Loading branch information
alesr committed Mar 12, 2017
1 parent 19328b8 commit fb9fecc
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
18 changes: 18 additions & 0 deletions sumsqrdiff.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package goexercises

// SumSqrDiff - https://projecteuler.net/problem=6
// The sum of the squares of the first ten natural numbers is,
// 12 + 22 + ... + 102 = 385
// The square of the sum of the first ten natural numbers is,
// (1 + 2 + ... + 10)2 = 552 = 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.
func SumSqrDiff(n int) int {
sumOfSq := 0 // Sum of the squares ie. 1^2+2^3...
sqSum := 0 // Square of the sum ie. (1+2+...)^3
for i := 1; i <= n; i++ {
sumOfSq += i * i
sqSum += i
}
return sqSum*sqSum - sumOfSq
}
27 changes: 27 additions & 0 deletions sumsqrdiff_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package goexercises

import (
"testing"
)

func TestSumSqrDiff(t *testing.T) {
testCases := []struct {
input, expected int
}{
{10, 2640},
{100, 25164150},
}
for _, test := range testCases {
observed := SumSqrDiff(test.input)
if observed != test.expected {
t.Errorf("for input '%d', expected '%d, observed '%d'\n",
test.input, test.expected, observed)
}
}
}

func BenchmarkSumSqrDiff(b *testing.B) {
for i := 0; i < b.N; i++ {
SumSqrDiff(100)
}
}

0 comments on commit fb9fecc

Please sign in to comment.