N4K5JOHMX4GDSYRZMVQBA432LTIG5AW7ST36JB2RD7MMCOCFN5WAC
// Package diffsquares is for searchnig the difference between the
// square of the sum and the sum of the squares for the first n natural numbers.
package diffsquares
// SquareOfSum returns the square of the sum of first n numbers.
func SquareOfSum(n int) int {
// Using the child Gauss trick
ret := (n * (n + 1)) / 2
return ret * ret
}
// SumOfSquares returns the summary of the square of first n numbers.
func SumOfSquares(n int) int {
//https://brilliant.org/wiki/sum-of-n-n2-or-n3/
ret := (n * (n + 1) * (2*n + 1)) / 6
return ret
}
// Difference returns the difference between SquareOfSum and SumOfSquare for n.
func Difference(n int) int {
return SquareOfSum(n) - SumOfSquares(n)
}
package diffsquares_test
import (
"diffsquares"
"testing"
)
func TestBruteSquareOfSum(t *testing.T) {
for _, test := range tests {
if s := diffsquares.BruteSquareOfSum(test.n); s != test.sqOfSum {
t.Fatalf("SquareOfSum(%d) = %d, want %d", test.n, s, test.sqOfSum)
}
}
}
func TestBruteSumOfSquares(t *testing.T) {
for _, test := range tests {
if s := diffsquares.BruteSumOfSquares(test.n); s != test.sumOfSq {
t.Fatalf("SumOfSquares(%d) = %d, want %d", test.n, s, test.sumOfSq)
}
}
}
func TestBruteDifference(t *testing.T) {
for _, test := range tests {
want := test.sqOfSum - test.sumOfSq
if s := diffsquares.BruteDifference(test.n); s != want {
t.Fatalf("Difference(%d) = %d, want %d", test.n, s, want)
}
}
}
// BenchmarkBrute functions on just a single number (100, from the original PE problem)
// to avoid overhead of iterating over tests.
func BenchmarkBruteSquareOfSum(b *testing.B) {
for i := 0; i < b.N; i++ {
diffsquares.BruteSquareOfSum(100)
}
}
func BenchmarkBruteSumOfSquares(b *testing.B) {
for i := 0; i < b.N; i++ {
diffsquares.BruteSumOfSquares(100)
}
}
func BenchmarkBruteDifference(b *testing.B) {
for i := 0; i < b.N; i++ {
diffsquares.BruteDifference(100)
}
}
package diffsquares
// BruteSquareOfSum returns the square of the sum of first N numbers.
// Brute force version.
func BruteSquareOfSum(N int) int {
var ret int
for i := 1; i <= N; i++ {
ret += i
}
return ret * ret
}
// BruteSumOfSquares returns the summary of the square of first N numbers.
// Brute force version.
func BruteSumOfSquares(N int) int {
var ret int
for i := 1; i <= N; i++ {
ret += i * i
}
return ret
}
// BruteDifference returns the difference between BruteSquareOfSum and BruteSumOfSquare for N.
func BruteDifference(N int) int {
return BruteSquareOfSum(N) - BruteSumOfSquares(N)
}