import java.util.Scanner;
class codeabbey145
{
public static void main(String[] Args)
{
Scanner input = new Scanner(System.in);
double A = 0;
double B = 0;
double M = 0;
System.out.println("\n\nHow many sets?");
int s = input.nextInt();
double X[] = new double[s];
for(int i = 0; i<s; i++)
{
System.out.println("A: ");
A = input.nextDouble();
System.out.println("B: ");
B = input.nextDouble();
System.out.println("M: ");
M = input.nextDouble();
X[i] = (Math.pow(A, B)) % M; //(A^B)%M
}
for(int j = 0; j<s; j++)
{
System.out.print(Math.round(X[j]) + " ");
}
}
}
我一直在尝试在 Codeabbey.com 上完成练习 145
模幂的计算公式为:(A^B)%M
我尽力将这个公式应用到我的代码中,但我得到的答案是不正确的。有人知道为什么会这样吗?
提前致谢
最佳答案
您的代码绝对正确:检查 here 。
也许您应该使用 BigInteger:
来处理大数字,从不建议使用 double。
这是工作示例:检查此 live demo
代码
public static void main(String[] Args) {
Scanner input = new Scanner(System.in);
System.out.println("\n\nHow many sets?");
int s = input.nextInt();
BigInteger[] X = new BigInteger[s];
for (int i = 0; i < s; i++) {
System.out.println("A: ");
BigInteger A = input.nextBigInteger();
System.out.println("B: ");
BigInteger B = input.nextBigInteger();
System.out.println("M: ");
BigInteger M = input.nextBigInteger();
X[i] = A.modPow(B, M); //(A^B)%M
}
for (int i = 0; i < X.length; i++) {
System.out.println(X[i]);
}
}
我已经在 CodeAbbey 上尝试过这个问题。 我的解决方案被接受了。
代码:
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.BigInteger;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main(String[] Args) {
Scanner input = new Scanner(System.in);
int s = input.nextInt();
BigInteger[] X = new BigInteger[s];
for (int i = 0; i < s; i++) {
BigInteger A = input.nextBigInteger();
BigInteger B = input.nextBigInteger();
BigInteger M = input.nextBigInteger();
X[i] = A.modPow(B, M);
}
for (int i = 0; i < X.length; i++) {
System.out.println(X[i]+" ");
}
}
}
关于java - Java 中的模幂问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31800079/