java - Java 中的模幂问题

标签 java modular exponentiation

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 上尝试过这个问题。 我的解决方案被接受了。

Solution accepted

代码:

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/

相关文章:

Java,模块化逆

c - 如何创建 C 头文件

c++ - 模幂 - 如何减少巨大的模数?

python - 以特定的 y 间隔绘制函数

haskell - Haskell 中的求幂

具有流式更新的 Java Swing 树

Java - 重新加载类时关闭套接字

java - itext多重签名

java - 为什么字节数组不能存储在java中的整数数组中

haskell - 在 Haskell 中使用带有列表列表的 map 时出现问题