【HDU6608 Fansblog】求很大很大的数的阶乘

Fansblog


Description

Farmer John keeps a website called ‘FansBlog’ .Everyday , there are many people visited this blog.One day, he find the visits has reached P , which is a prime number.He thinks it is a interesting fact.And he remembers that the visits had reached another prime number.He try to find out the largest prime number Q ( Q < P ) ,and get the answer of Q! Module P.But he is too busy to find out the answer. So he ask you for help. ( Q! is the product of all positive integers less than or equal to n: n! = n * (n-1) * (n-2) * (n-3) *… * 3 * 2 * 1 . For example, 4! = 4 * 3 * 2 * 1 = 24 )

Standard Input

First line contains an number T(1<=T<=10) indicating the number of testcases. Then T line follows,each contains a positive prime number P (1e9≤p≤1e14)

Standard Output

For each case output a line with one integer, means the factorial of Q modulo P for one line.

Sample Input

1 1000000007

Sample Output

328400734

emmm。。。。。。。。。。。。

首先, Q ! Q! Q! 是肯定不能从1乘过去的,也没有方法可以正着算过去。。。
于是聪明的zzy小公举就想,可不可以倒着推呢。
我们知道, P ! m o d P = 0 P! mod P=0 P!modP=0,好像可以从这里入手耶。对于P取模的话,其实也只需要在 P ! P! P!这里乘好多逆元~
但是 P ! m o d P = 0 P! mod P=0 P!modP=0。。。怎么乘也不行啊。。。
于是小公举就入手了数论四大玄学定理中的威尔逊定理!(但他比赛的时候并没有入手,居然自己瞎推推出来了神奇的 Q ! = p − ( Q + 1 ) − 1 ( Q + 2 ) − 1 . . . ( p − 2 ) − 1 ( p − 1 ) − 1 Q!=p-(Q+1)^{-1}(Q+2)^{-1}...(p-2)^{-1}(p-1)^{-1} Q!=p(Q+1)1(Q+2)1...(p2)1(p1)1
由此可见,瞎推还是很重要的,嗯。
那么传说中的威尔逊定理呢?
他告诉我们:

( p − 1 ) ! ≡ − 1 ( m o d p ) ( p -1 )! ≡ -1 ( mod p ) (p1)!1(modp)

于是我们就可以这么写,,然后这么算出来。。

Q ! [ ( Q + 1 ) ( Q + 2 ) . . . ( p − 1 ) ] = p − 1 ( m o d p ) Q![(Q+1)(Q+2)...(p-1)]=p-1(mod p) Q![(Q+1)(Q+2)...(p1)]=p1(modp)

Q ! ( Q + 1 ) ( Q + 2 ) . . . ( p − 2 ) = ( p − 1 ) ∗ ( p − 1 ) − 1 = 1 Q!(Q+1)(Q+2)...(p-2)=(p-1)*(p-1)^{-1}=1 Q!(Q+1)(Q+2)...(p2)=(p1)(p1)1=1

Q ! = 1 ∗ ( Q + 1 ) − 1 ( Q + 2 ) − 1 . . . ( p − 2 ) − 1 Q!=1*(Q+1)^{-1}(Q+2)^{-1}...(p-2)^{-1} Q!=1(Q+1)1(Q+2)1...(p2)1

由于P和Q不会离很远,于是直接这么乘,用大数乘法就好了~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值