Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created November 9, 2025 22:17
Show Gist options
  • Select an option

  • Save Ifihan/bf4871beb5890fc755cdb2358a8e2d21 to your computer and use it in GitHub Desktop.

Select an option

Save Ifihan/bf4871beb5890fc755cdb2358a8e2d21 to your computer and use it in GitHub Desktop.
Count Operations to Obtain Zero

Question

Approach

I keep performing the subtraction operation until either number becomes zero. In each step, I subtract the smaller number from the larger one and count how many operations it takes. Since this process is similar to finding the GCD using subtraction, it ends when one number hits zero.

Implementation

class Solution:
    def countOperations(self, num1: int, num2: int) -> int:
        count = 0
        while num1 > 0 and num2 > 0:
            if num1 >= num2:
                num1 -= num2
            else:
                num2 -= num1
            count += 1
        return count

Complexities

  • Time: O(max(num1, num2))
  • Space: O(1)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment