阶乘函数在 Python 中工作,为 Julia 返回 0

2022-01-23 00:00:00 python julia

问题描述

我在 Python 中定义了一个阶乘函数如下:

I define a factorial function as follows in Python:

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

print(fact(100))

在 Julia 中如下:

and as follows in Julia:

function fact(n)
    if n == 1
        n
    else
        n * fact(n-1)
    end
end

println(fact(100))

python 程序返回一个非常大的数字来评估 100(如预期的那样).Julia 返回 0.对于较小的数字(如 10),它们都可以工作.

The python program returns a very large number for the evaluation of 100 (as expected). Julia returns 0. With a smaller number (like 10) they both work.

我有两个问题:

  1. 为什么 Python 可以处理这个问题而 Julia 不行.
  2. 为什么 Julia 不抛出错误而只打印 0?


解决方案

没有人回答为什么 Julia 的结果是 0.

Nobody answers why the result in Julia is 0.

Julia 不检查整数乘法是否溢出,因此 64 位整数的乘法是在模 2^63 下执行的.请参阅此常见问题解答条目

Julia does not check integer multiplication for overflow and thus the multiplication for 64 bit integers is performed mod 2^63. See this FAQ entry

当你写出阶乘的乘法时,你得到

when you write out the multiplication for factorial you get

1*2*3*4*5*6*7*8*9*10*11*12*13*14*15*16*17*18*19*20*21*22*23*24*25*26*27*28*29*30*31*32*33*34*35*36*37*38*39*40*41*42*43*44*45*46*47*48*49*50*51*52*53*54*55*56*57*58*59*60*61*62*63*64*65*66*67*68*69*70*71*72*73*74*75*76*77*78*79*80*81*82*83*84*85*86*87*88*89*90*91*92*93*94*95*96*97*98*99*100

这也可以写成素因数

2^97 * 3^48 * 5^24 * 7^16 * 11^9 * 13^7 * 17^5 * 19^5 * 23^4 * 29^3 * 31^3 * 37^2 * 41^2 * 43^2 * 47^2 * 53^1 * 59^1 * 61^1 * 67^1 * 71^1 * 73^1 * 79^1 * 83^1 * 89^1 * 97^1

如果您查看 2 的指数,您会得到 97.模运算使您可以在计算的任何步骤执行 mod 功能,并且不会影响结果.2^97 mod 2^63 == 0 与链的其余部分相乘也是 0.

If you look at the exponent of 2 you get 97. Modular arithmetic gives that you can do the mod function at any step of the calculation, and it will not affect the result. 2^97 mod 2^63 == 0 which multiplied with the rest of the chain is also 0.

更新:我当然懒得在纸上做这个计算.

UPDATE: I was of course too lazy to do this calculation on paper.

d = Dict{Int,Int}()
for i=1:100
   for (k,v) in factor(i)
       d[k] = get(d,k,0) + v
   end
end
for k in sort(collect(keys(d)))
    print("$k^$(d[k])*")
end

Julia 在其标准库中有一个非常方便的 factor() 函数.

Julia has a very convenient factor() function in its standard library.

相关文章