Hamza Yussif
Hamza Yussif

Reputation: 27

Calculating modulo in Java

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

Upvotes: 0

Views: 2717

Answers (2)

Tobias Geiselmann
Tobias Geiselmann

Reputation: 2486

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

Upvotes: 0

Sweeper
Sweeper

Reputation: 273540

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

Upvotes: 4

Related Questions