阶乘的最后一个非零数字 [英] Last nonzero digit of a factorial
问题描述
我要确定阶乘的最后一个非零数字。
我试图解决它使用除法:10或其倍数除以数量
例:7! = 5040 => 4
所以,我把5040以10送4的结果。
不过,我们可以说,我们应该使用的逻辑,而不是阶乘(5040)的价值数7。
请让我知道我该怎么办呢?
- 计算n的素数分解!如下:
- 在每个黄金
P
< =N
,p的指数是
- 在每个黄金
- 从
2
的指数减去5
的指数,从原分解放弃所有的五岁以下儿童。 - 乘以剩余的素数分解模10.注意,这样做的时候,你可以用下面的等价:(对于我和GE 0)。单个产品也可以做模10如果必要的。
我用了一点空余时间来实现这个解决方案在bash。 (bash的好,为什么不呢?):
last_nonzero(){
局部n = $ 1
当地D = $(power_mod_10 3 $(count_factors $ N 3))
D = $((D * $(power_mod_10 2 $(($(count_factors $ N 2)
- $(count_factors $ N 5))))))
对于p在$(素数7 $ N)
做
D = $((D * $(power_mod_10 $ P $(count_factors $ N $ P))%10))
做完
回声$ D
}
count_factors(){
局部n = $ 1个P = $ 2
当地D = $((N / P))
当地Q = $ D
而((Q> = P));做
Q = $((Q / P))D = $((D + Q))
做完
回声$ D
}
power_mod_10(){
当地MODS = .......... 0161000101012300070901490009010187000309
本地P = $(($ 1%10))EXP = $(($ 2%,4 + 1))
回声$ {MODS:$ EXP $ P:1}
}
是的,最后一个是一个黑客攻击。
另外:有一个更好的递归解决方案。搜索 http://math.stackexchange.com ,甚至是谷歌。
I want to determine the last nonzero digit of a factorial.
I tried to solve it using division: Dividing the number by 10 or multiples thereof.
Ex : 7! = 5040 => 4
So I divide 5040 by 10 and get 4 as result.
But, let us say, we should use the number 7 in the logic instead of value of the factorial (5040).
Please let me know how can I do it?
- Compute the prime decomposition of n! as follows:
- for each prime
p
<=n
, the exponent of p is
- for each prime
- Subtract the exponent of
5
from the exponent of2
and discard all the fives from the prime decomposition. - Multiply the remaining prime decomposition modulo 10. Note that when doing this, you can use the following equivalence: (for i ≥ 0). The individual products can also be done mod 10 if necessary.
I used a bit of spare time to implement this solution in bash. (bash? well, why not?):
last_nonzero () {
local n=$1
local d=$(power_mod_10 3 $(count_factors $n 3))
d=$((d * $(power_mod_10 2 $(($(count_factors $n 2)
- $(count_factors $n 5))))))
for p in $(primes 7 $n)
do
d=$((d * $(power_mod_10 $p $(count_factors $n $p)) % 10))
done
echo $d
}
count_factors () {
local n=$1 p=$2
local d=$((n/p))
local q=$d
while ((q >= p)); do
q=$((q/p)) d=$((d+q))
done
echo $d
}
power_mod_10 () {
local mods=..........0161000101012300070901490009010187000309
local p=$(($1%10)) exp=$(($2%4+1))
echo ${mods:$exp$p:1}
}
Yes, the last one is a hack.
Also: There is an even better recursive solution. Search http://math.stackexchange.com, or even google.
这篇关于阶乘的最后一个非零数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!