PHP program to calculate the repeated subtraction of two numbers

Repeated subtraction is a method to find how many times one number can be subtracted from another until the result becomes less than the subtractor. This is mathematically equivalent to division and finding the quotient.

Example

Here's a PHP program that calculates repeated subtraction using a recursive approach ?

<?php
function repeated_sub($val_1, $val_2)
{
    if ($val_1 % $val_2 == 0)
        return floor(((int)$val_1 / $val_2));
    return floor(((int)$val_1 / $val_2) + repeated_sub($val_2, $val_1 % $val_2));
}

$val_1 = 1000;
$val_2 = 189;
print_r("The repeated subtraction results in ");
echo repeated_sub($val_1, $val_2);
?>
The repeated subtraction results in 18

How It Works

The function repeated_sub uses the Euclidean algorithm principle. It checks if the first value divides evenly by the second value. If yes, it returns the floor of the quotient. Otherwise, it recursively calls itself with the second value and the remainder, adding this to the current quotient.

For the values 1000 and 189, the function calculates how many times 189 can be subtracted from 1000, which is 5 times (189 × 5 = 945), leaving a remainder of 55. The process continues recursively until completion.

Conclusion

This recursive approach efficiently calculates repeated subtraction by leveraging division and modulo operations. The result represents the total number of subtractions needed to reduce the dividend below the divisor.

Updated on: 2026-03-15T09:07:46+05:30

315 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements