问题描述
我在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(如预期).朱莉娅返回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.
我有两个问题:
- 为什么Python不能处理这个问题,而Julia却不能.
- Julia为什么不抛出错误并只打印0?
推荐答案
没有人回答为什么Julia中的结果为0.
Nobody answers why the result in Julia is 0.
Julia不会检查整数乘法的溢出,因此64位整数的乘法是在mod 2 ^ 63上执行的.请参见此FAQ条目
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
写出阶乘的乘积时得到
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.
这篇关于阶乘函数在Python中有效,为Julia返回0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!