Count Operations to Obtain Zero
Problem
Given two non-negative integers num1 and num2, in each operation subtract the smaller from the larger (or do nothing if either is zero). Return the number of operations needed until at least one becomes zero.
num1 = 2, num2 = 33def count_operations(num1, num2):
ops = 0
while num1 and num2:
if num1 >= num2:
num1 -= num2
else:
num2 -= num1
ops += 1
return ops
function countOperations(num1, num2) {
let ops = 0;
while (num1 && num2) {
if (num1 >= num2) num1 -= num2;
else num2 -= num1;
ops++;
}
return ops;
}
class Solution {
public int countOperations(int num1, int num2) {
int ops = 0;
while (num1 != 0 && num2 != 0) {
if (num1 >= num2) num1 -= num2;
else num2 -= num1;
ops++;
}
return ops;
}
}
int countOperations(int num1, int num2) {
int ops = 0;
while (num1 && num2) {
if (num1 >= num2) num1 -= num2;
else num2 -= num1;
ops++;
}
return ops;
}
Explanation
This one is solved by directly simulating the rule the problem describes: keep subtracting the smaller number from the larger one and count how many times you do it.
The loop runs while num1 and num2 are both nonzero. Each pass compares the two: if num1 >= num2 we do num1 -= num2, otherwise num2 -= num1. Every subtraction adds 1 to ops. When one value hits zero, the loop stops and we return ops.
Why it works: the rule says to always shrink the bigger value by the smaller, and we follow that exactly, so the counter naturally matches the number of operations the problem asks for.
Example: num1 = 2, num2 = 3. Since 2 < 3, do num2 -= num1 giving (2, 1). Now 2 >= 1, do num1 -= num2 giving (1, 1). Then 1 >= 1 giving (0, 1). That is 3 operations.
This is the same repeated-subtraction idea behind Euclid's GCD, which is why it finishes quickly even for fairly large inputs.