Athavan Kanapuli Athavan Kanapuli - 9 months ago 38
Python Question

Golang Factorial Shows Wrong Result

I have converted a Python factorial function into a golang program . The Python code is as follows

def main():
n = input('Enter a number')
result = factorial(n)
print(result)

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)


And the Golang problem is as follows ,

package main

import "fmt"

func main() {
fmt.Println("Enter a Number ")
var n int64
var result int64
fmt.Scan(&n)
result = factorial(n)
fmt.Println(result)
}

func factorial(n int64) int64 {
//fmt.Println(n)
if n == 0 {
return int64(1)
}
//fmt.Println(n * factorial(n-1))
return int64(n * factorial(n-1))

}


The results of both the programs are same for small numbers.But for bigger numbers The Go output is zero. The Terminal output is as follows ,

enKats-MacBook-Air:Factorials venkat$ python factorial.py
Enter a number5
120
VenKats-MacBook-Air:Factorials venkat$ go run factorial.go
Enter a Number
5
120
VenKats-MacBook-Air:Factorials venkat$ python factorial.py
Enter a number99
933262154439441526816992388562667004907159682643816214685929638952175999932299156089414639761565182862536979208272237582511852109168640000000000000000000000
VenKats-MacBook-Air:Factorials venkat$ go run factorial.go
Enter a Number
99
0
VenKats-MacBook-Air:Factorials venkat$


What's wrong with the Go Program for larger numbers? Any help would be appreciated.

Answer Source

This is the result of overflow. Vanilla Python ints are arbitrarily sized. But if you use a sized int, e.g. 64 bit-ints using numpy for example, you get the same problem:

>>> import numpy as np
>>> def factorial(n):
...   if n == 0:
...     return np.int64(1)
...   else:
...     return n * factorial(n - np.int64(1))
...
>>> factorial(99)
__main__:5: RuntimeWarning: overflow encountered in long_scalars
0

I am not a golang programmer, but a quick search yielded the following from the standard library:

https://golang.org/pkg/math/big/