here is only basic implementation of problems for beginners. If you have any problem with any solution or any basic concept of programming or you want more efficient solution you can mail me.
my suggestion is not to copy and paste codes from here try to understand the logic and think why you were not able to solve it.

Monday 6 October 2014

Boring factorials

problem is here


This can be solved using Wilson theorem
   (1). if n>=p  ans would be 0
   (2). then we have to use Wilson's theorem
             (p-1)!     -1 (mod p)
             1*2*3*.........*(n-1)*(n)*..............*(p-1)     -1 (mod p)
             n!*(n+1)*...........*(p-1)      -1 (mod p)
             n!      -1*[(n+1)*...............(p-2)*(p-1)]^-1 (mod p)


#include<stdio.h>
long long power(long long a,long long b,long long m){
  long long x=1,y=a;
  while(b>0){
  if(b%2!=0){
  x=(x*y)%m;
  }
  y=(y*y)%m;
  b>>=1;
  }
  return x;
}
int main(){
  int t;
  long long n,p,i,result,z,x;
  scanf("%d",&t);
  while(t--){
  result=-1;
  scanf("%lld %lld",&n,&p);
  if(n>=p){
    printf("0\n");
    continue;
  }
  x=1;
  for(i=n+1;i<p;i++){
  x=(x*i)%p;
  }
    z=power(x,p-2,p);
    result=(result*z)%p;
  printf("%lld\n",p+result);
  }
  return 0;

}

No comments:

Post a Comment