2010网易有道难题5.24练习赛B-解题

写了半天的思路和文字,找不到了。这次就不写思路了,直接贴代码。分析问题时要注意内存溢出、运算效率。顺便说一句。网易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;
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值