大數相乘求和的模運算
題目如上圖,這是在程序設計或者ACM中常見的數學題目,結合前人經驗總結了一下。(開發語言c)
#include<stdio.h>
#define INT64 __int64
INT64 PowerMode(INT64 basenum, INT64 powernum, INT64 modenum){
//計算basenum^powernum % modenum
//a^(2c) = (a^c)^2;
//a^(2c+1) = a*((a^c)^2);
//比如a=3,b=13時,我們把b寫成二進制的形式13(10)=1101(2)
//我們從低位到高位運算,每運算一位可以將b右移一位,上面的例子可以轉化成3^13 = 3^1 * 3^4 * 3^8
//(a*b)%p = a%p * b%p %p
//(a^b)%p = (a%p)^b
//a^13%m=(a^8*a^4*a^1)%m=a^8%m * a^4%m * a^1%m %m
INT64 result = 1;
while(powernum){
if(powernum&1)
result = result * basenum % modenum;
basenum = basenum * basenum % modenum;
powernum>>=1;
}
return result;
}
INT64 MultiAdd(INT64 countnum, INT64 basenum, INT64 modenum){
//(a+b)%p = (a%p + b%p) %p
//
INT64 sum = 0;
for(int i=0; i<=countnum; i++){
sum += (countnum-i)%modenum * PowerMode(basenum,i,modenum) %modenum;
sum %= modenum;
}
return sum;
}
int main(){
INT64 testnum;
scanf("%I64d",&testnum);
while(testnum--){
INT64 n,m,x;
scanf("%I64d %I64d %I64d",&n,&m,&x);
INT64 value = MultiAdd(n,x,m);
printf("%I64d\n",value);
}
return 0;
}
本文出自 “詩意生活” 博客,請務必保留此出處http://whish.blog.51cto.com/10679902/1942323
大數相乘求和的模運算