Count Operations to Obtain Zero - Problem

You are given two non-negative integers num1 and num2.

In one operation, if num1 >= num2, you must subtract num2 from num1, otherwise subtract num1 from num2.

For example, if num1 = 5 and num2 = 4, subtract num2 from num1, thus obtaining num1 = 1 and num2 = 4. However, if num1 = 4 and num2 = 5, after one operation, num1 = 4 and num2 = 1.

Return the number of operations required to make either num1 = 0 or num2 = 0.

Input & Output

Example 1 — Basic Case
$ Input: num1 = 2, num2 = 3
Output: 3
💡 Note: Operation 1: 3 ≥ 2, so num2 = 3 - 2 = 1, now num1 = 2, num2 = 1. Operation 2: 2 ≥ 1, so num1 = 2 - 1 = 1, now num1 = 1, num2 = 1. Operation 3: 1 = 1, so num1 = 1 - 1 = 0. Total: 3 operations.
Example 2 — One Operation
$ Input: num1 = 10, num2 = 10
Output: 1
💡 Note: Since both numbers are equal, one operation makes one of them zero: 10 - 10 = 0. Total: 1 operation.
Example 3 — Multiple Operations
$ Input: num1 = 1, num2 = 5
Output: 5
💡 Note: 5-1=4, 4-1=3, 3-1=2, 2-1=1, 1-1=0. Total: 5 operations to make num1 zero.

Constraints

  • 0 ≤ num1, num2 ≤ 106

Visualization

Tap to expand
Count Operations to Obtain Zero INPUT num1 2 num2 3 Operation Rule: if num1 >= num2: num1 = num1 - num2 else: num2 = num2 - num1 Goal: Make num1=0 or num2=0 Count total operations num1 = 2, num2 = 3 Two positive integers ALGORITHM STEPS 1 Compare: 2 < 3 num2 = 3 - 2 = 1 num1=2, num2=1 2 Compare: 2 >= 1 num1 = 2 - 1 = 1 num1=1, num2=1 3 Compare: 1 >= 1 num1 = 1 - 1 = 0 num1=0, num2=1 4 Check Condition num1 = 0 [OK] STOP - Goal reached! Operations Counted: Step1 + Step2 + Step3 = 3 FINAL RESULT Total Operations 3 Final State: num1 = 0 num2 = 1 Operation Trace: Op1: (2,3) --> (2,1) Op2: (2,1) --> (1,1) Op3: (1,1) --> (0,1) Output: 3 [OK] Key Insight: This algorithm simulates the Euclidean GCD subtraction method. Each operation reduces one number by the value of the other. The process continues until one becomes zero. For optimal solution, we can use division to count multiple subtractions at once: operations += num1 / num2, then swap if needed. TutorialsPoint - Count Operations to Obtain Zero | Optimal Solution
Asked in
Amazon 15 Google 12
28.5K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen