Boring Factorials
given below code for dcepc11b spoj or boring factorial spoj.
here the problem is based on two main concepts
1 -> Wilson’s Theorem
2 -> Inverse modulo (It can be found by Extended Euclidean Algorithm , Fermat’s Little Theorem ,Euler’s Theorem)
here in this problem i have used Fermat's theorem
Now from this we can write :
Here my solution get accepted in 1.83 sec can any body help me in optimizing this solution or any other solution which get accepted in lower time please mail me @ raj.nishant360@gmail.com
#include <bits/stdc++.h> using namespace std; #define LL long long LL pow_mod(LL a,LL b,LL m) { LL x=1,y=a; while(b>0) { if(b & 1) x=(x*y)%m; y=(y*y)%m; b>>=1; } return x; } int main() { int t; scanf("%d",&t); while(t--) { LL n,p,i,result=-1,temp; scanf("%lld%lld",&n,&p); if(n>=p) { printf("0\n"); continue; } for(i=n+1;i<p;i++) { temp=pow_mod(i,p-2,p); result=(result*temp)%p; } printf("%lld\n",p+result); } return 0; }
Great explanation!! Before the inverse modulo part there was a -1 in multiplication how it is removed?
ReplyDeleteAlso at the end why you are adding the p to the answer?
Delete