doupa9062 2017-03-12 03:06
浏览 51
已采纳

Golang阶乘显示错误结果

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.

  • 写回答

1条回答 默认 最新

  • dosc9472 2017-03-12 03:15
    关注

    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/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥50 汇编语言除法溢出问题
  • ¥65 C++实现删除N个数据列表共有的元素
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波