写了半天的思路和文字,找不到了。这次就不写思路了,直接贴代码。分析问题时要注意内存溢出、运算效率。顺便说一句。网易POJ平台今天的表现太差了。
另外看了下Accept的结果, GCC的运行效率高于java 40 倍左右,也明显高于G++ 。
描述
计算a的b次方对9907取模的值。
输入
第一行有一个正整数T,表示有T组测试数据。
接下来T行,每行是一组测试数据,包含两个整数a和b。
其中T<=10000, 0 <=a,b < 2^31。
输出
有T行,依次输出每组数据的结果。
样例输入
3
1 2
2 3
3 4
样例输出
1
8
81
简略分析:
m= a % c
x = a^b % c = m^b %c
当b = 2n 则: x = ( m^n % c ) ^ 2 % c
当b = 2n+1 则: x = ((( m^n % c ) ^ 2 % c) * m )% c
我的代码:
package poj.youdao.b;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int line = new Integer(input.readLine().trim());
for(int i=0;i<line;i++){
String[] text = input.readLine().split("\\s");
int a = new Integer(text[0]);
int b = new Integer(text[1]);
System.out.println(getMod(a,b,9907));
}
input.close();
}
public static int getMod(int a, int b, int c) {
int halfB = b / 2;
int mod=0;
if(b<=1){
mod = a % c;
}
else{
mod = getMod(a, halfB, c);
if (b % 2 == 1) {
mod = (((mod * mod)%c) * (a%c) ) % c;
} else {
mod = (mod * mod ) % c;
}
}
return mod;
}
}