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

java - Java中的模幂问题-LMLPHP

码:

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]+" ");
        }
    }
}

08-04 13:10