【问题标题】:BigInteger problems大整数问题
【发布时间】:2014-01-24 22:51:32
【问题描述】:

您好,我正在研究 gcd 和反模运算的算法。

我必须使用 BigInteger 类,但我对此有一些问题。

那你能帮帮我吗?

问题是java程序不想用新的BigInteger输入覆盖旧的输入。

    import java.math.BigInteger;
    public class Gcd
 { 
public static void gcd(BigInteger a, BigInteger b){
    BigInteger  modulo =  b;
    BigInteger  wert = a;
    BigInteger  zwischenwert1 =  BigInteger.valueOf(1);
    BigInteger  zwischenwert2 = BigInteger.valueOf(0);

    BigInteger  zwischenwert3 = BigInteger.valueOf(0);
    BigInteger  zwischenwert4 = BigInteger.valueOf(1);
    BigInteger negativ = BigInteger.valueOf(-1);
    BigInteger  q;
    do{
        q = modulo.divide(wert);

        wert = modulo.subtract(wert.multiply(q));           
        zwischenwert3 = zwischenwert1.subtract(zwischenwert3.multiply(q));
        zwischenwert4 = zwischenwert2.subtract(zwischenwert4.multiply(q));

        modulo = negativ.multiply((wert.subtract(modulo)).divide(q));
        zwischenwert1 = negativ.multiply((zwischenwert3.subtract(zwischenwert1)).divide(q));
        zwischenwert2 = negativ.multiply((zwischenwert4.subtract(zwischenwert2)).divide(q));         

    }while((modulo.signum()>1)&&(wert.signum()>1));
      System.out.println("gcd("+a+","+b+") = "+zwischenwert3+" * "+b+ " + "+ zwischenwert4+" * "+ a+" = "+((BigInteger.valueOf(b).multiply(zwischenwert3)).add((BigInteger.valueOf(a).multiply(zwischenwert4)))));
    if (((BigInteger.valueOf(b).multiply(zwischenwert3)).add((BigInteger.valueOf(a).multiply(zwischenwert4)))).signum()==1)
        System.out.println("Inverse "+a+" mod "+b+" is"+zwischenwert4);
    else
        System.out.println("no Inverse!");

}}

【问题讨论】:

  • BigInteger.valueOf(a) 是什么?这应该是a
  • 哦,我很抱歉你是对的,它应该是 a 和下一个 lin b 但这并没有解决我链接 BigInteger 值的问题

标签: java algorithm biginteger modulo bluej


【解决方案1】:

您不必编写自己的 gcd 方法,因为它在 BigInteger 类中可用。

a.gcd(b)

【讨论】:

  • modInverse 也是如此。
  • Yes he does,因为这可能是学校的练习。
【解决方案2】:

在java中,所有对象都通过引用的副本传递,这意味着如果您将a传递给您的函数,然后更改分配给引用a的值,则原始值将保持不变,因为您实际上并没有可以访问原始参考,但可以访问它的副本。实际上,您需要返回一个对新对象的引用,让它转义函数。

例如:

public BigInteger mod(BigInteger a, BigInteger b){
  // .... create new value x
  return x;
}

顺便说一句,根据Wikipedia page,您几乎可以应用以下内容:

function gcd(a, b)
  while b ≠ 0
     t := b
     b := a mod b
     a := t
  return a

【讨论】:

  • 感谢您的快速答复!但我该怎么做呢?抱歉,我是 Java 世界的新手
  • 顺便说一句,您知道BigInteger 类有一个计算gcd 的方法吗?
  • 所以每次我计算类似wert = modulo.subtract(wert.multiply(q));我必须写return wert; ?
  • 仅当您准备好退出该功能时。 return 语句使程序退出当前函数。
猜你喜欢
  • 1970-01-01
  • 2021-09-20
  • 2011-07-05
  • 2013-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多