代码之家  ›  专栏  ›  技术社区  ›  parsa.ni

在java中转换为BigInteger

  •  0
  • parsa.ni  · 技术社区  · 2 年前

    我想用java将这个函数代码重写为BigInteger类:

     static int power(int x, int y, int p)
        {
            int res = 1; // Initialize result
     
            while (y > 0) {
     
                // If y is odd, multiply x with result
                if ((y & 1) != 0)
                    res = res * x;
     
                // y must be even now
                y = y >> 1; // y = y/2
                x = x * x; // Change x to x^2
            }
            return res % p;
        }
    

    我尝试并编写了以下代码:

    static BigInteger power(BigInteger x, BigInteger y, BigInteger p) {
            BigInteger res = BigInteger.ONE; // Initialize result
    
            while (y.compareTo(BigInteger.ZERO) == 1) {   
    
                // If y is odd, multiply x with result
                if ((y.and(BigInteger.ONE)) != BigInteger.ZERO)  
                    res = res.multiply(x);  
    
                // y must be even now
                y = y.shiftRight(1); // y = y/2   
                x = x.multiply(x); // Change x to x^2
            }
            return res.mod(p);
        }
    

    但当我测试输入“功率(2,5,13)”时,输出是11,但正确答案是6。

    我检查了我写的代码好几次,但都找不到问题。你能帮我输出正确的答案代码吗。

    2 回复  |  直到 2 年前
        1
  •  1
  •   Elliott Frisch    2 年前

    该方法已实现为 BigInteger.modPow(BigInteger, BigInteger) 。我会这么称呼它,就像

    static BigInteger power(BigInteger x, BigInteger y, BigInteger p) {
        return x.modPow(y, p);
    }
    

    其次,不能用三个调用方法 int 价值观你需要 BigInteger 论据。喜欢

    public static void main(String[] args) {
        System.out.println(power(BigInteger.valueOf(2),
                BigInteger.valueOf(5),
                BigInteger.valueOf(13)));
    }
    

    我明白了

    6
    
        2
  •  0
  •   Unmitigated    2 年前

    您应该将引用类型与进行比较 .equals == 至于基元。

    if (!BigInteger.ZERO.equals(y.and(BigInteger.ONE)))
    

    此外,您应该只考虑的结果的符号 compareTo ; 不要直接与1这样的固定值进行比较。

    while (y.compareTo(BigInteger.ZERO) > 0)