KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I am trying to implement this bit of code: func factorial(x int) (result int) { if x == 0 { result = 1; } else { result = x * factorial(x - 1); } return; } as a big.Int so as to make it effective for larger values of x. The following is returning a value of 0 for fmt.Println(factorial(r)) The factorial of 7 should be 5040? Any ideas on what I am doing wrong? package main import "fmt" import "math/big" func main() { fmt.Println("Hello, playground") //n := big.NewInt(40) r := big.NewInt(7) fmt.Println(factorial(r)) } func factorial(n *big.Int) (result *big.Int) { //fmt.Println("n = ", n) b := big.NewInt(0) c := big.NewInt(1) if n.Cmp(b) == -1 { result = big.NewInt(1) } if n.Cmp(b) == 0 { result = big.NewInt(1) } else { // return n * factorial(n - 1); fmt.Println("n = ", n) result = n.Mul(n, factorial(n.Sub(n, c))) } return result } This code on go playground: http://play.golang.org/p/yNlioSdxi4
Tags (comma-separated)
Save Edits
Cancel