Given two constructive integers N and M, the duty is to seek out the variety of completely different GCDs which may be fashioned by including an integer Ok to each N and M, the place Ok ≥ 0.
Examples:
Enter: N = 8, M = 4
Output: 3
Rationalization: If Ok = 0, then GCD(8, 4) = 4,
If Ok = 1, then GCD(9, 5) = 1,
If Ok = 2, then GCD(10, 6) = 2Enter: N = 7, M = 10
Output: 2
Rationalization: If Ok = 0, then GCD(7, 10) = 1,
If Ok = 2, then GCD(9, 12) = 3
Method: The issue may be solved based mostly on the next mathematical thought:
The utmost worth of GCD fashioned after including any worth of Ok can be abs(N – M).
Aside from the above consequence if every other GCD is fashioned, that can be an ideal divisor of abs(N – M).
Comply with the steps under to implement the above thought:
- Discover absolutely the distinction between N and M (say X).
- Discover the variety of distinctive divisors of the X.
- Return this worth because the required reply.
Beneath is the implementation of the above method:
Java
|
Time Complexity: O(sqrt(abs(N – M)))
Auxiliary House: O(sqrt(abs(N – M)))