Program to count minimum number of operations required to make numbers non coprime in Python?

Two numbers are coprime if their greatest common divisor (GCD) is 1. This program finds the minimum number of increment/decrement operations needed to make two numbers non-coprime (GCD > 1).

Problem Understanding

Given two numbers A and B, we can perform operations to increment or decrement either number by 1. The goal is to find the minimum operations required so that GCD(A, B) ? 1.

Example

If A = 8 and B = 9, we can increment B to 10. Then GCD(8, 10) = 2, which is not 1, so they become non-coprime in just 1 operation.

Algorithm

The solution follows this logic ?

  • If numbers are already non-coprime (GCD ? 1), return 0 operations

  • If either number is even, return 1 operation (make the other even too)

  • Otherwise, check if 1 operation on either number creates a non-coprime pair

  • If not possible in 1 operation, return 2 operations

Implementation

from math import gcd

class Solution:
    def solve(self, a, b):
        # Already non-coprime
        if gcd(a, b) != 1:
            return 0
        
        # If either number is even, we can make them non-coprime in 1 step
        if a % 2 == 0 or b % 2 == 0:
            return 1
        
        # Check if 1 operation makes them non-coprime
        if (gcd(a + 1, b) != 1 or gcd(a - 1, b) != 1 or 
            gcd(a, b - 1) != 1 or gcd(a, b + 1) != 1):
            return 1
        
        # Otherwise, 2 operations are needed
        return 2

# Test the solution
ob = Solution()
A = 8
B = 9
result = ob.solve(A, B)
print(f"Minimum operations for A={A}, B={B}: {result}")
Minimum operations for A=8, B=9: 1

How It Works

For A = 8 and B = 9 ?

  • GCD(8, 9) = 1, so they are coprime

  • Since 8 is even, we can make 9 even in 1 operation

  • Incrementing 9 to 10 gives GCD(8, 10) = 2 ? 1

Additional Test Cases

# Test multiple cases
test_cases = [(8, 9), (15, 25), (7, 11), (4, 6)]

for a, b in test_cases:
    result = ob.solve(a, b)
    print(f"A={a}, B={b} ? Minimum operations: {result}")
A=8, B=9 ? Minimum operations: 1
A=15, B=25 ? Minimum operations: 0
A=7, B=11 ? Minimum operations: 2
A=4, B=6 ? Minimum operations: 0

Conclusion

This algorithm efficiently finds the minimum operations by checking if numbers are already non-coprime, then leveraging the fact that even numbers share a common factor of 2. The maximum operations needed is always 2.

Updated on: 2026-03-25T12:13:03+05:30

381 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements