Minimum number of increment / decrements required to be performed on one of the two given numbers to make them non-coprime

by Nitikesh Pattanayak
168 views
A+A-
Reset

Given two positive integers A and B, the task is to find the minimum number of increments/decrements required to be performed on either A or B to make both the numbers non-coprime.

Examples:

Input: A = 12, B = 3
Output: 0
Explanation:
As 12 & 3 are already non-coprimes, so the minimum count of increment/decrement operation required is 0.

Input: A = 7, B = 17
Output: 2

Approach: The given problem can be solved based on the following observations:

  • If A and B have Greatest Common Divisor greater than 1 then no increment or decrement is to be performed, as numbers are already non-coprime.
  • Now, check for the difference of 1 in both directions for A as well as B. Hence it requires only a single step to convert any number to an even number.
  • If none of the above two cases applies then 2 increments/decrements operations are required to make the numbers A and B to their nearest even number so that the numbers become non-co primes.

Based on the above observations, follow the steps below to solve the problem:

  • If the GCD of A and B is not equal to 1, then print 0 as no operation is required.
  • Else if the GCD of one of the pair {{A + 1, B}, {A – 1, B}, {A, B + 1}, {A, B – 1}} is not equal to 1, then print 1 as only one operations is required.
  • Otherwise, print 2.

Below is the implementation of the above approach:

C++

  

#include <bits/stdc++.h>

using namespace std;

  

int makeCoprime(int a, int b)

{

    

    if (__gcd(a, b) != 1)

        return 0;

  

    

    

    

    if (__gcd(a - 1, b) != 1

        or __gcd(a + 1, b) != 1

        or __gcd(b - 1, a) != 1

        or __gcd(b + 1, a) != 1)

        return 1;

  

    

    return 2;

}

  

int main()

{

    int A = 7, B = 17;

    cout << makeCoprime(A, B);

  

    return 0;

}

Time Complexity: O(log(A, B))
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

You may also like

Leave a Reply

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More

-
00:00
00:00
Update Required Flash plugin
-
00:00
00:00
Verified by MonsterInsights