Stein's Algorithm to find GCD in C++In this article, you will learn about the Stein's Algorithm to find GCD in C++ with its algorithm and examples. What is the Stein's Algorithm?Stein's Algorithm is an algorithm that finds the greatest common divisor of two non-negative integers, which is also known as the binary GCD algorithm. Stein's algorithm uses subtraction, comparisons, and arithmetic shifts instead of division. It is an effective way to determine two numbers' greatest common divisor (GCD). Even though Israeli programmer and scientist Josef Stein initially published that approach in its current form in 1967, it's possible that ancient Chinese people were aware of it as early as the second century BCE. Examples:Input: a = 24 b = 30 Output: 6 Input: a = 36, b = 60 Output: 12 Algorithm:The algorithm finds the GCD of two nonnegative numbers x and y by repeatedly applying these identities:
Stein's approach to find the GCD of two numbers, gcd (a, b):-
Example 1:Let us take an example to find GCD using Stein's Algorithm in C++. Output: Complexity Analysis: Time Complexity:
Auxiliary Space:
Example 2:Let us take another example to find GCD using Stein's Algorithm: Output: Complexity Analysis: Time Complexity:
Auxiliary Space:
Benefits of Stein's Algorithm over Euclid's Algorithm to find GCD of two numbers:
|
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India