Java BigInteger modInverse and modPow

I am trying to understand the behavior of modPow and modInverse of the Java BigInteger class, as they do not work as I expected. Maybe I missed something simple, so here is a very simple piece of code:

BigInteger a = BigInteger.valueOf(2); BigInteger b = BigInteger.valueOf(5); BigInteger n1 = new BigInteger(32, 100, new SecureRandom()); System.out.println("n = " + n1); System.out.println("a^b = " + a.modPow(b, n1) + " ;; (a^b)^(b^-1) = " + a.modPow(b, n1).modPow(b.modInverse(n1), n1)); 

The output I get is:

 n = 2664021049 (This is a random prime, can change each run) a^b = 32 ;; (a^b)^(b^-1) = 4 

Now I would expect 4 in the last line to be 2 , since this is (a^b)^(1/b) = a^(b*(1/b)) = a

If it also works in a modular field?

What am I doing wrong?

+5
source share
3 answers

I suppose there is confusion that

 b.modInverse(n1) == 532804210 

because (5 * 532804210) mod 2664021049 == 1

After that:

 a.modPow(b, n1) == 32 

=> 32 ^ b.modInverse (n1) mod 2664021049

=> 32 ^ 532804210 mod 2664021049 == 4

0
source

Short answer: invert b mod p-1 , not mod p . (If b not reversibly mod p-1 , the problem is unsolvable.)


While in the case x ≡ y (mod p) , then x^z ≡ y^z (mod p) , we cannot conclude that z^x ≡ z^y (mod p) . For example, by Fermat’s small theorem,

 x^p ≡ x (mod p) 

although p ≡ 0 (mod p) and x^0 = 1 .

However, Fermat’s Little Theorem gives us a solution. For integers x and y and a prime module p , if we can find the multiplicative inverse z for y mod p-1 , then

 (x^y)^z = x^(yz) = x^(k(p-1) + 1) for some k = (x^(p-1))^k * x 

If x ≡ 0 (mod p) , then (x^(p-1))^k * x ≡ x (mod p) , since both sides are congruent to 0.

If x !≡ 0 (mod p) , then we can get x^(p-1) ≡ 1 (mod p) from x^p ≡ x (mod p) , and we have (x^(p-1))^k * x ≡ 1^k * x ≡ x (mod p) .

Thus, (x^y)^z ≡ x (mod p) .

On the other hand, if y not invertible mod p-1 , then it turns out that we cannot restore x from x^y , since there are several possible values ​​of x . For example, with x = 2, y = 3, p = 7 we have x^y ≡ 1 (mod p) , but x can be 1 .

0
source

Refer to this to understand the behavior of modPow () and modInverse () of the BigInteger class.

modPow:

 BigInteger numOne = new BigInteger("5"); BigInteger numTwo = new BigInteger("20"); BigInteger exponent = new BigInteger("3"); BigInteger MP = numOne.modPow(exponent, numTwo); System.out.println(numOne + " ^ " + exponent + " mod " + numTwo + " = " + MP); 

modInverse:

 BigInteger numOne = new BigInteger("7"); BigInteger numTwo = new BigInteger("20"); BigInteger MI = numOne.modInverse(numTwo); System.out.println(numOne + " ^-1 mod " + numTwo + " = " + MI); 
-1
source

Source: https://habr.com/ru/post/1261246/


All Articles