0

I can't figure out why the calculation of the mod not going right, I have a=23, b=86609, c=17 where (d=a^c mod b). So the result should be 16559 according to the calculator but I get 49432?

public class Mod {

  public static void main(String[] args) {
    int a=23;
    int b=86609;
    int c=17;
    double d= (Math.pow(a,c)%b);
    System.out.print(d);
  }
}
KarelG
  • 5,176
  • 4
  • 33
  • 49
  • 3
    23 ^ 17 is outside the precision of a `double`. Try using [`BigInteger`](https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html) for calculations like these. – Phylogenesis Aug 17 '17 at 12:21

2 Answers2

4

The problem is not at the modulus part. You get the wrong result as soon as you go to the pow part.

23^17 is 1.41050039560662968926103 × 10^23 to be precise. See what Java think it equals:

1.4105003956066297E23

Obviously that's not precise enough.

A solution to this problem is BigInteger:

BigInteger a = new BigInteger("23");
BigInteger b = a.modPow(new BigInteger("17"), new BigInteger("86609"));
System.out.println(b);

Remember to import java.math.BigInteger;!

Sweeper
  • 213,210
  • 22
  • 193
  • 313
0

23^17 is too big for a double. Calculate it with BigInteger:

public class Main {

    public static void main(String[] args) {
        int a = 23;
        int b = 86609;
        int c = 17;
        BigInteger big = BigInteger.valueOf(a);
        big = big.pow(c);
        big = big.mod(BigInteger.valueOf(b));
        System.out.print(big);
    }  
}
Tobias Geiselmann
  • 2,139
  • 2
  • 23
  • 36