Posts A%M == B%M
Post
Cancel

A%M == B%M

Problem Description

Given two integers A and B, find the greatest possible positive integer M, such that A % M = B % M.

Solution

This problem needs some derivation:

A%M = B%M
=> A%M - B%M = 0
=> A%M - B%M + M = M //add M on both sides
=> (A%M - B%M + M)%M = M%M //take mod on both sides
=> (A-B)%M = 0 //Since (A%M - B%M + M)%M equals (A-B)%M Modular Arithematic

So, we can say that if A%M=B%M, then A-B must be divisible by M. In other words, M is a multiple of A-B. Obviously, the largest number which can divide A-B will be the absolute of (A-B).

1
2
3
4
5
public class Solution {
    public int solve(int A, int B) {
        return Math.abs(A-B);
    }
}
This post is licensed under CC BY 4.0 by the author.