Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the remainder of a big numbers in java

Tags:

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);
    }
}
like image 378
user3276091 Avatar asked Nov 28 '22 11:11

user3276091


1 Answers

According to the Fermat's little theorem:

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

and so:

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

Therefore, you don't need to do this heavy calculations. Just maths.

like image 189
Konstantin Yovkov Avatar answered Dec 16 '22 17:12

Konstantin Yovkov