Repeated subtraction among two numbers
Given a pair of positive numbers x and y. We repeatedly subtract the smaller of the two integers from greater one until one of the integers becomes 0. The task is to count number of steps to before we stop (one of the numbers become 0).
Examples :
Input : x = 5, y = 13
Output : 6
Explanation : There are total 6 steps before
we reach 0:
(5,13) --> (5,8) --> (5,3) --> (2,3)
--> (2,1) --> (1,1) --> (1,0).
Input : x = 3, y = 5
Output : 4
Explanation : There are 4 steps:
(5,3) --> (2,3) --> (2,1) --> (1,1) --> (1,0)
Input : x = 100, y = 19
Output : 13
A simple solution is to actually follow the process and count the number of steps.
A better solution is to use below steps. Let y be the smaller of two numbers
1) if y divides x then return (x/y)
2) else return ( (x/y) + solve(y, x%y) )
Illustration :
If we start with (x, y) and y divides x then the answer will be (x/y) since we can subtract y form x exactly (x/y) times.
For the other case, we take an example to see how it works: (100, 19)
We can subtract 19 from 100 exactly [100/19] = 5 times to get (19, 5).
We can subtract 5 from 19 exactly [19/5] = 3 times to get (5, 4).
We can subtract 4 from 5 exactly [5/4] = 1 times to get (4, 1).
We can subtract 1 from 4 exactly [4/1] = 4 times to get (1, 0)
hence a total of 5 + 3 + 1 + 4 = 13 steps.
Below is implementation based on above idea.
C++
#include<bits/stdc++.h>
using namespace std;
int countSteps( int x, int y)
{
if (x%y == 0)
return x/y;
return x/y + countSteps(y, x%y);
}
int main()
{
int x = 100, y = 19;
cout << countSteps(x, y);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int countSteps( int x,
int y)
{
if (x % y == 0 )
return x / y;
return x / y + countSteps(y, x % y);
}
public static void main (String[] args)
{
int x = 100 , y = 19 ;
System.out.println(countSteps(x, y));
}
}
|
Python3
import math
def countSteps(x, y):
if (x % y = = 0 ):
return math.floor(x / y);
return math.floor((x / y) +
countSteps(y, x % y));
x = 100 ;
y = 19 ;
print (countSteps(x, y));
|
C#
using System;
class GFG
{
static int countSteps( int x,
int y)
{
if (x % y == 0)
return x / y;
return x / y + countSteps(y, x % y);
}
static public void Main ()
{
int x = 100, y = 19;
Console.WriteLine(countSteps(x, y));
}
}
|
PHP
<?php
function countSteps( $x , $y )
{
if ( $x % $y == 0)
return floor (((int) $x / $y ));
return floor (((int) $x / $y ) +
countSteps( $y , $x % $y ));
}
$x = 100;
$y = 19;
echo countSteps( $x , $y );
?>
|
Javascript
<script>
function countSteps(x, y)
{
if (x%y == 0)
return Math.floor(x/y);
return Math.floor(x/y) + countSteps(y, x%y);
}
let x = 100, y = 19;
document.write(countSteps(x, y));
</script>
|
Output :
13
Time Complexity: O(log(n)), where N is min(x,y).
Auxiliary Space: O(logn) for recursive stack space.
Last Updated :
30 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...