Skip to content

Commit

Permalink
Merge 9ff331f into 1e4e0f4
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Jan 26, 2019
2 parents 1e4e0f4 + 9ff331f commit dc855b8
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -166,3 +166,4 @@ problems from
* [Day 153](https://github.com/vaskoz/dailycodingproblem-go/issues/316)
* [Day 154](https://github.com/vaskoz/dailycodingproblem-go/issues/320)
* [Day 155](https://github.com/vaskoz/dailycodingproblem-go/issues/322)
* [Day 156](https://github.com/vaskoz/dailycodingproblem-go/issues/325)
27 changes: 27 additions & 0 deletions day156/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package day156

import (
"math"
)

// MinSquared returns the smallest number
// of squared integers which sum to n.
// Runs in exponential time.
func MinSquared(n int) int {
return minSquared(n, 0, n)
}

func minSquared(n, level, minSoFar int) int {
if n <= 3 {
return n
}
end := int(math.Sqrt(float64(n))) + 1
for i := end; i > 0; i-- {
if x := i * i; x <= n {
if y := 1 + minSquared(n-x, level+1, minSoFar); y < minSoFar {
minSoFar = y
}
}
}
return minSoFar
}
27 changes: 27 additions & 0 deletions day156/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package day156

import "testing"

var testcases = []struct {
n, expected int
}{
{13, 2},
{27, 3},
}

func TestMinSquared(t *testing.T) {
t.Parallel()
for _, tc := range testcases {
if result := MinSquared(tc.n); result != tc.expected {
t.Errorf("For N=%d Expected %v got %v", tc.n, tc.expected, result)
}
}
}

func BenchmarkMinSquared(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, tc := range testcases {
MinSquared(tc.n)
}
}
}

0 comments on commit dc855b8

Please sign in to comment.