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); } }
doubledon't actually behave like integers. Java true integer type java.math.BigInteger.
double
java.math.BigInteger
public static void main(String[] args) { BigInteger a = new BigInteger("3").pow(561); System.out.println(a.mod(new BigInteger("561"))); }
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.
BigInteger :
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 )
-Math.pow(a, b) % m ( ) , :Math.pow(a, b) % m = Math.pow(a, b-1) % m * aJava:
Math.pow(a, b) % m
Math.pow(a, b) % m = Math.pow(a, b-1) % m * a
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, .
a*(m-1)
int
BigInteger#modPow
- double. BigDecimal
BigDecimal bigDecimal=new BigDecimal("3").pow(561); BigDecimal[] bigDecimal1=bigDecimal.divideAndRemainder(new BigDecimal("561")); System.out.println(bigDecimal1[1]);
divideAndRemainder() , , . - , .
:
3