快速幂的求解-java方法(int范围之内)
思想就是,将十进制数化成二进制数。其它就是很简单了。
如:2的11次幂,11的二进制位1011,所以2(11) = 2(2(0) + 2(1) + 2(3));
具体实现步骤,看代码比较简单
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner cin = new Scanner(System.in);
//底数
int a = cin.nextInt();
//指数
int b = cin.nextInt();
int sum = 1;
int temp = a;
while(b != 0)
{
//取其末位
if((b & 1) != 0)
{
sum = sum * temp;
}
temp = temp * temp;
//除其末位
b = b>>1;
}
System.out.print(sum);
}
}
1.经典题目:
输入t,mod,n。t表示测试个数,mod需要除以这个数,n表示以下几行
输入n行,每行两个数字,x,y 求这n行里x的y次方的累加和除以mod,得到余数
输出余数。
实现代码如下:
import java.util.Scanner;
public class Main
{
static int m;
public static void main(String []args)
{
Scanner cin = new Scanner(System.in);
int T = cin.nextInt();
for(int i = 0; i < T; i++)
{
m = cin.nextInt();
int n = cin.nextInt();
int output = 0;
for(int j = 0; j < n; j++)
{
int a = cin.nextInt();
int b = cin.nextInt();
output = (output + Mod(a,b))%m;
//在这里要注意:不用
/*
output += Mod(a,b)%m;
output = output%Mod;
*/
}
System.out.println(output);
}
}
static int Mod(int a,int b)
{
int result = 1;
int temp = a;
while(b != 0)
{
temp = temp % m;//这一步不能不写,不写可能爆栈
if((b & 1) != 0)
{
result = (result%m)*(temp%m);//分别除以m,防止爆栈
}
temp = temp*temp%m;//除了m,防止爆栈
b = b>>1;
}
return result;
}
}
import java.util.Scanner; publicclass Main { staticint m; public static void main(String []args) { Scanner cin = new Scanner(System.in); int T = cin.nextInt(); for(int i = 0; i < T; i++) { m = cin.nextInt(); int n = cin.nextInt(); int output = 0; for(int j = 0; j < n; j++) { int a = cin.nextInt(); int b = cin.nextInt(); output = (output + Mod(a,b))%m; } System.out.println(output); } } static int Mod(int a,int b) { int result = 1; int temp = a; while(b != 0) { temp = temp % m; if((b & 1) != 0) { result = (result%m)*(temp%m); } temp = temp*temp%m; b = b>>1; } return result; } }