mirror of
https://github.com/cubixle/codekata-golang.git
synced 2026-04-24 19:54:43 +01:00
21: amicable numbers
This commit is contained in:
56
21_amicable_numbers/amicable_test.go
Normal file
56
21_amicable_numbers/amicable_test.go
Normal file
@@ -0,0 +1,56 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func Test_sumOfDivisors(t *testing.T) {
|
||||
tt := []struct {
|
||||
name string
|
||||
input int
|
||||
want int
|
||||
}{
|
||||
{
|
||||
"220",
|
||||
220,
|
||||
284,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tt {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got := sumOfDivisors(tc.input)
|
||||
if got != tc.want {
|
||||
t.Errorf("sumOfDivisors() = %d, want %d", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_isAmicableNumber(t *testing.T) {
|
||||
tt := []struct {
|
||||
name string
|
||||
input int
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
"220",
|
||||
220,
|
||||
true,
|
||||
},
|
||||
{
|
||||
"221",
|
||||
221,
|
||||
false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tt {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got := isAmicableNumber(tc.input)
|
||||
if got != tc.want {
|
||||
t.Errorf("isAmicableNumber() = %v, want %v", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
34
21_amicable_numbers/main.go
Normal file
34
21_amicable_numbers/main.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func main() {
|
||||
var nums []int
|
||||
sum := 0
|
||||
for i := 1; i < 10000; i++ {
|
||||
if isAmicableNumber(i) {
|
||||
nums = append(nums, i)
|
||||
sum += i
|
||||
}
|
||||
}
|
||||
fmt.Println("sum:", sum, "nums:", nums)
|
||||
}
|
||||
|
||||
func sumOfDivisors(input int) int {
|
||||
sum := 0
|
||||
for i := 1; i <= input/2; i++ {
|
||||
if input%i == 0 {
|
||||
sum += i
|
||||
}
|
||||
}
|
||||
return sum
|
||||
}
|
||||
|
||||
func isAmicableNumber(input int) bool {
|
||||
da := sumOfDivisors(input)
|
||||
db := sumOfDivisors(da)
|
||||
if da == db {
|
||||
return false
|
||||
}
|
||||
return input == db
|
||||
}
|
||||
Reference in New Issue
Block a user