Skip to content

Commit

Permalink
Merge 0c95f86 into d8d2dea
Browse files Browse the repository at this point in the history
  • Loading branch information
vaskoz committed Jan 14, 2020
2 parents d8d2dea + 0c95f86 commit ad95602
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -416,4 +416,5 @@ problems from
* [Day 417](https://github.com/vaskoz/dailycodingproblem-go/issues/842)
* [Day 418](https://github.com/vaskoz/dailycodingproblem-go/issues/844)
* [Day 419](https://github.com/vaskoz/dailycodingproblem-go/issues/846)
* [Day 420](https://github.com/vaskoz/dailycodingproblem-go/issues/848)

28 changes: 28 additions & 0 deletions day420/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package day420

// PerfectNth returns the n-th perfect number.
// A perfect number is one where the digits sum to 10.
// A panic will happen if the argument is less than 1.
func PerfectNth(n int) int {
if n < 1 {
panic("n must be greater than 0")
}

perfectNum := 10 // 10 is the seed value.
for n != 0 {
perfectNum += 9
digits := perfectNum
sum := 0

for digits != 0 {
sum += (digits % 10)
digits /= 10
}

if sum == 10 {
n--
}
}

return perfectNum
}
41 changes: 41 additions & 0 deletions day420/problem_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package day420

import "testing"

// nolint
var testcases = []struct {
n, expected int
}{
{1, 19},
{2, 28},
{10, 109},
}

func TestPerfectNth(t *testing.T) {
t.Parallel()

for _, tc := range testcases {
if result := PerfectNth(tc.n); result != tc.expected {
t.Errorf("Expected %v got %v", tc.expected, result)
}
}
}

func TestPerfectNthPanic(t *testing.T) {
t.Parallel()

defer func() {
if err := recover(); err == nil {
t.Errorf("Expected a panic for an argument less than 1")
}
}()
PerfectNth(0)
}

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

0 comments on commit ad95602

Please sign in to comment.