How to get the remainder of a large number in java

is there any solution to this problem? why it returns 541 instead of 3.

public class Test {
    public static void main(String[] args) {
        double a = Math.pow(3, 561);

        // it returns 541 instead of 3
        System.out.println(a % 561);
    }
}
+4
source share
5 answers

doubledon't actually behave like integers. Java true integer type java.math.BigInteger.

public static void main(String[] args) {
    BigInteger a = new BigInteger("3").pow(561);
    System.out.println(a.mod(new BigInteger("561")));
}
+6
source

According to Fermat’s little theorem :

Math.pow(a, p) % p == a % p

so:

Math.pow(3, 561) % 561 = 3 % 561 = 3

Therefore, you do not need to do these heavy calculations. Just math.

+11
source

BigInteger :

import java.math.BigInteger;

public class BigModPow
{
    public static void main(String[] args)
    {
        BigInteger b = new BigInteger("3");
        BigInteger e = new BigInteger("561");
        BigInteger m = new BigInteger("560");
        BigInteger result = b.modPow(e, m);
        System.out.println(result);
    }
}

(EDIT: modulo , , , , 561 )

+6

-
Math.pow(a, b) % m ( ) , :
Math.pow(a, b) % m = Math.pow(a, b-1) % m * a
Java:

private int modExp(int a, int b, int m) {
    if (b == 0) return 1;
    if (b == 1) return a % m;
    return (a * modExp(a, b-1, m)) % m;
}

, a*(m-1) int. BigInteger#modPow, .

+3

- double. BigDecimal

 BigDecimal bigDecimal=new BigDecimal("3").pow(561);
 BigDecimal[] bigDecimal1=bigDecimal.divideAndRemainder(new BigDecimal("561"));
 System.out.println(bigDecimal1[1]);

divideAndRemainder() , , . - , .

:

3
+3

All Articles