Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert to BigInteger in java

i want to rewrite this function code to BigInteger class in java:

 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;
    }

I tried and wrote the following code:

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);
    }

But when I tested for example input "power(2, 5, 13)", output is 11, however the correct answer is 6.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I checked the code I wrote several times, but I can’t find the problem. Can you please help me to output the correct answer code.

>Solution :

You should compare reference types with .equals, not == as for primitives.

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

In addition, you should only consider the sign of the result of compareTo; do not directly compare to a fixed value like 1.

while (y.compareTo(BigInteger.ZERO) > 0)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading