题目描述
Lucy give you three number a,b,c.
You should tell Lucy the answer of 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.
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;
}
本文介绍了一种快速计算a*b%c的方法,通过对b的二进制位进行判断,使用类似快速幂的思想来减少计算复杂度。
338

被折叠的 条评论
为什么被折叠?



