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).
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) )
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.
This article is contributed by Shubham Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- How to swap two numbers without using a temporary variable?
- Lucky Numbers
- Ugly Numbers
- Write a program to add two numbers in base 14
- Count of Binary Digit numbers smaller than N
- Program for Fibonacci numbers
- Average of a stream of numbers
- Add two numbers without using arithmetic operators
- To find sum of two numbers without using any operator
- Count numbers that don't contain 3
- Count numbers with same first and last digits
- Russian Peasant (Multiply two numbers using bitwise operators)
- Write a function that generates one of 3 numbers according to given probabilities
- Print squares of first n natural numbers without using *, / and -
- Print all increasing sequences of length k from first n natural numbers
- Count numbers from 1 to n that have 4 as a digit
- Compute sum of digits in all numbers from 1 to n
- Count factorial numbers in a given range
- Total number of non-decreasing numbers with n digits
- Count of n digit numbers whose sum of digits equals to given sum