您的位置:首页 > 其它

2017年省赛前最后一水 Problem C: a*b%c

2017-05-13 12:42 309 查看


题目描述

Lucy give you three number a,b,c.
You should tell Lucy the answer of a*b%c


输入

The first line of the input gives the number of test cases, T(1<T<1000). T test cases follow.
For each test case.
One line contains three integer a,b,c(0<a,b,c<1e18)


输出

For each test case, output a single line "Case #x: y", where x is the case number, starting from 1. And y is the answer.


样例输入

2

2 3 5

3 3 3


样例输出

Case #1: 1

Case #2: 0


分析: 

类似于求快速幂   

(a*b)%c   进行转化

(a*b)%c  =  (a*(2x1 +2x2+2x3+……+2xn))%c  =  (a*2x1+a*2x2+a*2x3+……+a*2xn)%c  =   (a*2x1)%c+(a*2x2)%c+( a*2x3)%c+……+(
a*2xn)%c




在b的每个二进制位上  判断是否加上 a的 2x  倍  (快速幂是乘上a的 2n 方)

代码如下:

#include <stdio.h>
long long fun(long long a,long long b,long long c){
long long sum=0;
while (b){
if(b%2){//                 判断b的二进制位是否为1
sum=(sum+a)%c;
}
b/=2;
a=(2*a)%c;
}
return sum;
}
int main (){
long long a,b,c;
int t;
scanf("%d",&t);
int Case=1;
while (t--){
scanf ("%lld%lld%lld",&a,&b,&c);
printf ("Case #%d: %lld\n",Case++,fun(a,b,c));
}
return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: