Skip to content

Commit

Permalink
add method factorial with tree
Browse files Browse the repository at this point in the history
Signed-off-by: deemak <[email protected]>
  • Loading branch information
deemakuzovkin committed Jun 15, 2021
1 parent dbc7cb5 commit eca5c00
Show file tree
Hide file tree
Showing 3 changed files with 152 additions and 50 deletions.
103 changes: 56 additions & 47 deletions .idea/workspace.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

39 changes: 39 additions & 0 deletions pkg/combinatorics/factorial.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,42 @@ func FactorialInt(n int64) int64 {
func FactorialString(n int64) string {
return Factorial(n).String()
}

/*FactorialTree *big.Int*/
func FactorialTree(n int64) *big.Int {
if n < 0 {
return big.NewInt(0)
}
if n == 0 {
return big.NewInt(1)
}
if n == 1 || n == 2 {
return big.NewInt(n)
}
return factorialTreeExecute(big.NewInt(2), big.NewInt(n))
}

/*FactorialTree string*/
func FactorialTreeString(n int64) string {
return FactorialTree(n).String()

}
func factorialTreeExecute(n, m *big.Int) *big.Int {
if n.CmpAbs(m) == 1 {
return big.NewInt(1)
}
if n.CmpAbs(m) == 0 {
return n
}
var temp, tempR big.Int
if temp.Sub(m, n).CmpAbs(big.NewInt(1)) == 0 {
return tempR.Mul(n, m)
}
var mod, modR, modr, result big.Int
mod.Add(n, m)
modR.Quo(&mod, big.NewInt(2))
resLeft := factorialTreeExecute(n, &modR)
modr.Add(&modR, big.NewInt(1))
resRight := factorialTreeExecute(&modr, m)
return result.Mul(resLeft, resRight)
}
60 changes: 57 additions & 3 deletions pkg/combinatorics/factorial_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package combinatorics

import (
"math/big"
"reflect"
"testing"
)

Expand All @@ -14,11 +16,11 @@ func TestFactorial(t *testing.T) {
want int64
}{
{
name: "Factorial 4! = 24",
name: "Factorial 10! = 24",
args: args{
n: 399168,
n: 10,
},
want: 24,
want: 3628800,
},
}
for _, tt := range tests {
Expand All @@ -29,3 +31,55 @@ func TestFactorial(t *testing.T) {
})
}
}

func TestFactorialTree(t *testing.T) {
type args struct {
n int64
}
tests := []struct {
name string
args args
want *big.Int
}{
{
name: "1000000!",
args: args{
n: 1000000,
},
want: big.NewInt(3628800),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := FactorialTree(tt.args.n); !reflect.DeepEqual(got, tt.want) {
t.Errorf("FactorialTree() = %v, want %v", got, tt.want)
}
})
}
}

func TestFactorialTreeString(t *testing.T) {
type args struct {
n int64
}
tests := []struct {
name string
args args
want string
}{
{
name: "1000000!",
args: args{
n: 1000000,
},
want: ``,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := FactorialTreeString(tt.args.n); got != tt.want {
t.Errorf("FactorialTreeString() = %v, want %v", got, tt.want)
}
})
}
}

0 comments on commit eca5c00

Please sign in to comment.