[英]Modular Exponentiation Issue in Java
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
我尽力将这个公式实现到代码中,但是得到的答案不正确。 有人知道为什么会这样吗?
提前致谢
您的代码是完全正确的: 在此处检查。
可能应该使用BigInteger:
处理大量数字时,绝对不建议使用double。
这是工作示例:检查此现场演示
码
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]+" ");
}
}
}
该值很可能太大而无法容纳double
,因此它们会溢出。 最好的选择可能是使用BigInteger
对象来实现。
BigInteger
具有pow
和mod
函数,可用于计算。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.