我使用 Bigintegers 的简单计算不起作用

My simple calculation with Bigintegers are not working

我需要计算这个:2894135^3787313 mod 4028033

正如您在下面看到的,我尝试使用 BigInteger,因为我的数字非常大。

import java.lang.Math;
import java.util.Scanner;
public class BigInteger extends Number implements Comparable<BigInteger>
{
  public static void main(String[] args)
  {
  BigInteger result=new BigInteger(Math.pow(2894135,3787313) % 4028033);
    System.out.println(result);
  }
}

错误:

/tmp/java_Wcf144/BigInteger.java:19: error: BigInteger is not abstract and does not override abstract method doubleValue() in Number public class BigInteger extends Number implements Comparable ^ /tmp/java_Wcf144/BigInteger.java:24: error: constructor BigInteger in class BigInteger cannot be applied to given types;
BigInteger result=new BigInteger(Math.pow(2894135,3787313) % 4028033); ^ required: no arguments found: double reason: actual and formal argument lists differ in length 2 errors

您还没有在 class 中实现 doubleValue() 方法。 而且你还需要用其他名称重命名你的主要class,Big Integer是一个单独的对象。

你为什么还要创建一个 BigInteger class。

BigInteger 已在 Java 中定义,请使用它

https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html

此外,对 BigInteger 进行所有操作,而不是最后将它们转换为 BigInteger。

阿比

两个问题:第一个是关于 BigInteger 的误用 class。

您声明了您的 自己的 BigInteger class,抱歉,这没有多大意义。如果您希望能够使用任意大小的 Integer 值;使用 现有 java.math.BigInteger class.

从那里开始:

BigInteger result=new BigInteger(Math.pow(2894135,3787313) % 4028033);

不是计算个BigInteger对象。

您正在使用 int 文字来计算一个值;以及您打算用作创建单个 BigInteger 的 ctor 参数的结果。

你可以选择:

BigInteger op1 = new BigInteger(2894135)
BigInteger op2 = new BigInteger(3787313);
BigInteger op3 = new BigInteger(4028033);
BigInteger result = op1.modpow(op2, op3); 

相反。取决于您打算使用的号码;您可能会也可能不会像以前那样进行 "pow" 计算;使用 Math.pow() 并处理 double 文字。但是以上内容适用于适合 JVM 的 any 数字。

即使解决了错误,你也会得到错误的答案,因为 Math.pow(2894135,3787313),这将导致 double 中的 overflow,并且它将 return 双 [ 的最大可能值=15=].

所以需要全部转换成BigInteger之后再进行操作。

import java.lang.Math;
import java.util.Scanner;
import java.math.BigInteger;
public class Main
{
  public static void main(String[] args)
  {
        BigInteger a=BigInteger.valueOf(2894135);
        BigInteger b=BigInteger.valueOf(3787313);
        BigInteger m=BigInteger.valueOf(4028033);
        BigInteger result=a.modPow(b,m); //calculates a^b %m
        System.out.println(result);
  }
}

编辑: 如果您想以更优化的方式执行此操作,则可以使用 Modular Exponentiation 的概念。这将提供 O(log(exponent)) 复杂度的输出。在这里你不能使用更大的值,因为它可能导致 overflow in long 最终给出错误的结果。

代码:

public class Main
{
  public static void main(String[] args)
  {
        long a=2894135;
        long b=3787313;
        long m=4028033;

        long result=modularExponentiation(a,b,m);
        System.out.println(result);
  }

    static long modularExponentiation(long a,long b,long m)
    {
        long result=1;
        while(b>0)
        {
            if(b % 2 ==1)
                result=(result * a)%m;
            a=(a*a)%m;
            b=b/2;
        }
        return result;
    }
}