-
Notifications
You must be signed in to change notification settings - Fork 32
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
70 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
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,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 | ||
} |
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,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) | ||
} | ||
} | ||
} |