mirror of
https://github.com/cubixle/codekata-golang.git
synced 2026-04-30 14:38:47 +01:00
sum square difference
This commit is contained in:
@@ -0,0 +1,23 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
fmt.Println("sum square difference of 100 is", SquareSum(100)-SumOfSquares(100))
|
||||||
|
}
|
||||||
|
|
||||||
|
func SquareSum(n int) int {
|
||||||
|
var sum int
|
||||||
|
for i := 1; i <= n; i++ {
|
||||||
|
sum += i
|
||||||
|
}
|
||||||
|
return sum * sum
|
||||||
|
}
|
||||||
|
|
||||||
|
func SumOfSquares(n int) int {
|
||||||
|
var sum int
|
||||||
|
for i := 1; i <= n; i++ {
|
||||||
|
sum += i * i
|
||||||
|
}
|
||||||
|
return sum
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestSumOfSquares(t *testing.T) {
|
||||||
|
tt := []struct {
|
||||||
|
name string
|
||||||
|
input int
|
||||||
|
want int
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
"1",
|
||||||
|
1,
|
||||||
|
1,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"10",
|
||||||
|
10,
|
||||||
|
385,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"5",
|
||||||
|
5,
|
||||||
|
1 + 4 + 9 + 16 + 25,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tt {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
got := SumOfSquares(tc.input)
|
||||||
|
if got != tc.want {
|
||||||
|
t.Errorf("SumOfSquares(%d)=%d, want %d", tc.input, got, tc.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSquareSum(t *testing.T) {
|
||||||
|
tt := []struct {
|
||||||
|
name string
|
||||||
|
input int
|
||||||
|
want int
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
"1",
|
||||||
|
1,
|
||||||
|
1,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"5",
|
||||||
|
5,
|
||||||
|
15 * 15,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"10",
|
||||||
|
10,
|
||||||
|
3025,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tt {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
got := SquareSum(tc.input)
|
||||||
|
if got != tc.want {
|
||||||
|
t.Errorf("SquareSum(%d)=%d, want %d", tc.input, got, tc.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user