Athavan Kanapuli Athavan Kanapuli - 1 year ago 68
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)

def factorial(n):
if n == 0:
return 1
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
result = factorial(n)

func factorial(n int64) int64 {
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
Enter a number5
VenKats-MacBook-Air:Factorials venkat$ go run factorial.go
Enter a Number
VenKats-MacBook-Air:Factorials venkat$ python
Enter a number99
VenKats-MacBook-Air:Factorials venkat$ go run factorial.go
Enter a Number
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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download