2

As We all know, modulo operation finds the remainder of division of one number by another.

I'm strruggling to figure out the correct way to get value of modulo.

a mod b = c

It's easy to find c if a >= 0. But, if a < 0, it's confusing me.

One day, I read in my lecturer notes if -75 mod 26 = 3.

Then, I create a simple program in java to find the result of -75 mod 26. The program compiles and prints result: -23.

So, what is the right way to find c if a < 0?

Belows is code I've tried:

public class modulo {
    public static void main(String [] args){
        int divide = -75;  

        int val = divide % 26; 

        System.out.println(divide+" % 26 = "+ val);

    }
}
Speaky
  • 185
  • 1
  • 3
  • 15

1 Answers1

0

Why won't you get absolute value from both before division?

public class modulo {
    public static void main(String [] args){
        int divide = -75;  
        int val = Math.abs(divide) % Math.abs(26); 
        System.out.println(divide+" % 26 = "+ val);
    }
}

...or simply get abs value from the result (with rounding)?

Math.round( result );
Miron Balcerzak
  • 886
  • 10
  • 21