0

I wrote the following code to calculate n!modulo p...Given that n and p are close...but its running in a rather funny way, cant figure out the bug..There is some overflow somewhere..The constraints are 1 < P <= 2*10^9

1 <= N <= 2*10^9 though it runs fine for few cases...what could be the error.I have used

(a/b)mod p = ((a mod p)*(b^(p-2))mod p)mod p

as p is prime....and wilsons theorem that (p-1)! mod p = p-1

#include<bits/stdc++.h>
#define _ ios_base::sync_with_stdio(0);cin.tie(0);
using namespace std;
unsigned int pow(unsigned int a, unsigned n,unsigned int p) {
unsigned int ret = 1;
while(n) {
if((n&1)== 1) ret=(ret*a)%p;
a=a%p;
a=(a*a)%p;
 n=n>>1;
}
return ret;
}
int main(){_
int t;
cin>>t;
while(t--){
    unsigned int n,p;
    long long int r;
    cin>>n>>p;
    r=p-1;
    if(n>=p){
        cout<<"0\n";
    }
    else{
        for(unsigned int i=p-1;i>n;i--){
            r=((long long)r*pow(i,p-2,p))%p;

        }
        cout<<r<<"\n";
    }
}   
return 0;
}
user103260
  • 99
  • 2
  • 9

1 Answers1

1

21! is 51090942171709440000, while 2^64 is only 1844674407370955161: so if unsigned long long is a 64-bit quantity (as is likely), it doesn't fit.

gsg
  • 9,167
  • 1
  • 21
  • 23