-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add sumsqrdiff solution, unit test and benchmark
- Loading branch information
Showing
2 changed files
with
45 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} |