簡體   English   中英

Java中的模冪問題

[英]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具有powmod函數,可用於計算。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM