mirror of
https://github.com/cubixle/codekata-golang.git
synced 2026-04-24 18:34:42 +01:00
53: combinatoric selections
This commit is contained in:
46
53_combinatoric_selections/main.go
Normal file
46
53_combinatoric_selections/main.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/big"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func main() {
|
||||
result := 0
|
||||
limit, _ := (&big.Int{}).SetString("1000000", 0)
|
||||
nLimit := 100
|
||||
for i := 1; i <= nLimit; i++ {
|
||||
for j := 0; j <= i; j++ {
|
||||
bi, _ := (&big.Int{}).SetString(strconv.Itoa(i), 0)
|
||||
fi := factorialOf(bi)
|
||||
bj, _ := (&big.Int{}).SetString(strconv.Itoa(j), 0)
|
||||
fj := factorialOf(bj)
|
||||
bk, _ := (&big.Int{}).SetString(strconv.Itoa(i-j), 0)
|
||||
fk := factorialOf(bk)
|
||||
mik := fj.Mul(fj, fk)
|
||||
dvk := mik.Div(fi, mik)
|
||||
if x := dvk.Add(dvk, limit.Neg(limit)); x.Int64() >= 0 {
|
||||
result++
|
||||
}
|
||||
}
|
||||
}
|
||||
fmt.Println(result)
|
||||
}
|
||||
|
||||
func factorialOf(n *big.Int) *big.Int {
|
||||
one, _ := (&big.Int{}).SetString("1", 0)
|
||||
if n.Int64() <= 2 {
|
||||
return one
|
||||
}
|
||||
p, _ := (&big.Int{}).SetString("1", 0)
|
||||
i, _ := (&big.Int{}).SetString("2", 0)
|
||||
for {
|
||||
p = p.Mul(p, i)
|
||||
if i.String() == n.String() {
|
||||
break
|
||||
}
|
||||
i = i.Add(i, one)
|
||||
}
|
||||
return p
|
||||
}
|
||||
41
53_combinatoric_selections/main_test.go
Normal file
41
53_combinatoric_selections/main_test.go
Normal file
@@ -0,0 +1,41 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"math/big"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func Test_factorialOf(t *testing.T) {
|
||||
type args struct {
|
||||
n *big.Int
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
want *big.Int
|
||||
}{
|
||||
{
|
||||
"test1",
|
||||
args{(&big.Int{}).SetInt64(0)},
|
||||
(&big.Int{}).SetInt64(1),
|
||||
},
|
||||
{
|
||||
"test2",
|
||||
args{(&big.Int{}).SetInt64(3)},
|
||||
(&big.Int{}).SetInt64(6),
|
||||
},
|
||||
{
|
||||
"test2",
|
||||
args{(&big.Int{}).SetInt64(5)},
|
||||
(&big.Int{}).SetInt64(120),
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := factorialOf(tt.args.n); !reflect.DeepEqual(got, tt.want) {
|
||||
t.Errorf("factorialOf() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user