Stein's Algorithm for finding GCD
Last Updated :
12 Feb, 2025
Stein's algorithm or binary GCD algorithm is an algorithm that computes the greatest common divisor of two non-negative integers. Stein’s algorithm replaces division with arithmetic shifts, comparisons, and subtraction.
Examples:
Input: a = 17, b = 34
Output : 17
Input: a = 50, b = 49
Output: 1
Algorithm to find GCD using Stein's algorithm gcd(a, b)
The algorithm is mainly an optimization over standard Euclidean Algorithm for GCD
- If both a and b are 0, gcd is zero gcd(0, 0) = 0.
- gcd(a, 0) = a and gcd(0, b) = b because everything divides 0.
- If a and b are both even, gcd(a, b) = 2*gcd(a/2, b/2) because 2 is a common divisor. Multiplication with 2 can be done with bitwise shift operator.
- If a is even and b is odd, gcd(a, b) = gcd(a/2, b). Similarly, if a is odd and b is even, then
gcd(a, b) = gcd(a, b/2). It is because 2 is not a common divisor. - If both a and b are odd, then gcd(a, b) = gcd(|a-b|/2, b). Note that difference of two odd numbers is even
- Repeat steps 3–5 until a = b, or until a = 0. In either case, the GCD is power(2, k) * b, where power(2, k) is 2 raise to the power of k and k is the number of common factors of 2 found in step 3.
C++
// Iterative C++ program to
// implement Stein's Algorithm
#include <bits/stdc++.h>
using namespace std;
// Function to implement
// Stein's Algorithm
int gcd(int a, int b)
{
/* GCD(0, b) == b; GCD(a, 0) == a,
GCD(0, 0) == 0 */
if (a == 0)
return b;
if (b == 0)
return a;
/*Finding K, where K is the
greatest power of 2
that divides both a and b. */
int k;
for (k = 0; ((a | b) & 1) == 0; ++k)
{
a >>= 1;
b >>= 1;
}
/* Dividing a by 2 until a becomes odd */
while ((a & 1) == 0)
a >>= 1;
/* From here on, 'a' is always odd. */
do
{
/* If b is even, remove all factor of 2 in b */
while ((b & 1) == 0)
b >>= 1;
/* Now a and b are both odd.
Swap if necessary so a <= b,
then set b = b - a (which is even).*/
if (a > b)
swap(a, b); // Swap u and v.
b = (b - a);
}while (b != 0);
/* restore common factors of 2 */
return a << k;
}
// Driver code
int main()
{
int a = 34, b = 17;
printf("Gcd of given numbers is %d\n", gcd(a, b));
return 0;
}
Java
// Iterative Java program to
// implement Stein's Algorithm
import java.io.*;
class GFG {
// Function to implement Stein's
// Algorithm
static int gcd(int a, int b)
{
// GCD(0, b) == b; GCD(a, 0) == a,
// GCD(0, 0) == 0
if (a == 0)
return b;
if (b == 0)
return a;
// Finding K, where K is the greatest
// power of 2 that divides both a and b
int k;
for (k = 0; ((a | b) & 1) == 0; ++k)
{
a >>= 1;
b >>= 1;
}
// Dividing a by 2 until a becomes odd
while ((a & 1) == 0)
a >>= 1;
// From here on, 'a' is always odd.
do
{
// If b is even, remove
// all factor of 2 in b
while ((b & 1) == 0)
b >>= 1;
// Now a and b are both odd. Swap
// if necessary so a <= b, then set
// b = b - a (which is even)
if (a > b)
{
// Swap u and v.
int temp = a;
a = b;
b = temp;
}
b = (b - a);
} while (b != 0);
// restore common factors of 2
return a << k;
}
// Driver code
public static void main(String args[])
{
int a = 34, b = 17;
System.out.println("Gcd of given "
+ "numbers is " + gcd(a, b));
}
}
// This code is contributed by Nikita Tiwari
Python
# Iterative Python 3 program to
# implement Stein's Algorithm
# Function to implement
# Stein's Algorithm
def gcd(a, b):
# GCD(0, b) == b; GCD(a, 0) == a,
# GCD(0, 0) == 0
if (a == 0):
return b
if (b == 0):
return a
# Finding K, where K is the
# greatest power of 2 that
# divides both a and b.
k = 0
while(((a | b) & 1) == 0):
a = a >> 1
b = b >> 1
k = k + 1
# Dividing a by 2 until a becomes odd
while ((a & 1) == 0):
a = a >> 1
# From here on, 'a' is always odd.
while(b != 0):
# If b is even, remove all
# factor of 2 in b
while ((b & 1) == 0):
b = b >> 1
# Now a and b are both odd. Swap if
# necessary so a <= b, then set
# b = b - a (which is even).
if (a > b):
# Swap u and v.
temp = a
a = b
b = temp
b = (b - a)
# restore common factors of 2
return (a << k)
# Driver code
a = 34
b = 17
print("Gcd of given numbers is ", gcd(a, b))
# This code is contributed by Nikita Tiwari.
C#
// Iterative C# program to implement
// Stein's Algorithm
using System;
class GFG {
// Function to implement Stein's
// Algorithm
static int gcd(int a, int b)
{
// GCD(0, b) == b; GCD(a, 0) == a,
// GCD(0, 0) == 0
if (a == 0)
return b;
if (b == 0)
return a;
// Finding K, where K is the greatest
// power of 2 that divides both a and b
int k;
for (k = 0; ((a | b) & 1) == 0; ++k)
{
a >>= 1;
b >>= 1;
}
// Dividing a by 2 until a becomes odd
while ((a & 1) == 0)
a >>= 1;
// From here on, 'a' is always odd
do
{
// If b is even, remove
// all factor of 2 in b
while ((b & 1) == 0)
b >>= 1;
/* Now a and b are both odd. Swap
if necessary so a <= b, then set
b = b - a (which is even).*/
if (a > b) {
// Swap u and v.
int temp = a;
a = b;
b = temp;
}
b = (b - a);
} while (b != 0);
/* restore common factors of 2 */
return a << k;
}
// Driver code
public static void Main()
{
int a = 34, b = 17;
Console.Write("Gcd of given "
+ "numbers is " + gcd(a, b));
}
}
// This code is contributed by nitin mittal
JavaScript
<script>
// Iterative JavaScript program to
// implement Stein's Algorithm
// Function to implement
// Stein's Algorithm
function gcd( a, b)
{
/* GCD(0, b) == b; GCD(a, 0) == a,
GCD(0, 0) == 0 */
if (a == 0)
return b;
if (b == 0)
return a;
/*Finding K, where K is the
greatest power of 2
that divides both a and b. */
let k;
for (k = 0; ((a | b) & 1) == 0; ++k)
{
a >>= 1;
b >>= 1;
}
/* Dividing a by 2 until a becomes odd */
while ((a & 1) == 0)
a >>= 1;
/* From here on, 'a' is always odd. */
do
{
/* If b is even, remove all factor of 2 in b */
while ((b & 1) == 0)
b >>= 1;
/* Now a and b are both odd.
Swap if necessary so a <= b,
then set b = b - a (which is even).*/
if (a > b){
let t = a;
a = b;
b = t;
}
b = (b - a);
}while (b != 0);
/* restore common factors of 2 */
return a << k;
}
// Driver code
let a = 34, b = 17;
document.write("Gcd of given numbers is "+ gcd(a, b));
// This code contributed by gauravrajput1
</script>
PHP
<?php
// Iterative php program to
// implement Stein's Algorithm
// Function to implement
// Stein's Algorithm
function gcd($a, $b)
{
// GCD(0, b) == b; GCD(a, 0) == a,
// GCD(0, 0) == 0
if ($a == 0)
return $b;
if ($b == 0)
return $a;
// Finding K, where K is the greatest
// power of 2 that divides both a and b.
$k;
for ($k = 0; (($a | $b) & 1) == 0; ++$k)
{
$a >>= 1;
$b >>= 1;
}
// Dividing a by 2 until a becomes odd
while (($a & 1) == 0)
$a >>= 1;
// From here on, 'a' is always odd.
do
{
// If b is even, remove
// all factor of 2 in b
while (($b & 1) == 0)
$b >>= 1;
// Now a and b are both odd. Swap
// if necessary so a <= b, then set
// b = b - a (which is even)
if ($a > $b)
swap($a, $b); // Swap u and v.
$b = ($b - $a);
} while ($b != 0);
// restore common factors of 2
return $a << $k;
}
// Driver code
$a = 34; $b = 17;
echo "Gcd of given numbers is " .
gcd($a, $b);
// This code is contributed by ajit
?>
OutputGcd of given numbers is 17
Time Complexity: O(N*N)
Auxiliary Space: O(1)
[Expected Approach 2] Recursive Implementation - O(N*N) Time and O(N*N) Space
C++
// Recursive C++ program to
// implement Stein's Algorithm
#include <bits/stdc++.h>
using namespace std;
// Function to implement
// Stein's Algorithm
int gcd(int a, int b)
{
if (a == b)
return a;
// GCD(0, b) == b; GCD(a, 0) == a,
// GCD(0, 0) == 0
if (a == 0)
return b;
if (b == 0)
return a;
// look for factors of 2
if (~a & 1) // a is even
{
if (b & 1) // b is odd
return gcd(a >> 1, b);
else // both a and b are even
return gcd(a >> 1, b >> 1) << 1;
}
if (~b & 1) // a is odd, b is even
return gcd(a, b >> 1);
// reduce larger number
if (a > b)
return gcd((a - b) >> 1, b);
return gcd((b - a) >> 1, a);
}
// Driver code
int main()
{
int a = 34, b = 17;
printf("Gcd of given numbers is %d\n", gcd(a, b));
return 0;
}
Java
// Recursive Java program to
// implement Stein's Algorithm
import java.io.*;
class GFG {
// Function to implement
// Stein's Algorithm
static int gcd(int a, int b)
{
if (a == b)
return a;
// GCD(0, b) == b; GCD(a, 0) == a,
// GCD(0, 0) == 0
if (a == 0)
return b;
if (b == 0)
return a;
// look for factors of 2
if ((~a & 1) == 1) // a is even
{
if ((b & 1) == 1) // b is odd
return gcd(a >> 1, b);
else // both a and b are even
return gcd(a >> 1, b >> 1) << 1;
}
// a is odd, b is even
if ((~b & 1) == 1)
return gcd(a, b >> 1);
// reduce larger number
if (a > b)
return gcd((a - b) >> 1, b);
return gcd((b - a) >> 1, a);
}
// Driver code
public static void main(String args[])
{
int a = 34, b = 17;
System.out.println("Gcd of given"
+ "numbers is " + gcd(a, b));
}
}
// This code is contributed by Nikita Tiwari
Python
# Recursive Python 3 program to
# implement Stein's Algorithm
# Function to implement
# Stein's Algorithm
def gcd(a, b):
if (a == b):
return a
# GCD(0, b) == b; GCD(a, 0) == a,
# GCD(0, 0) == 0
if (a == 0):
return b
if (b == 0):
return a
# look for factors of 2
# a is even
if ((~a & 1) == 1):
# b is odd
if ((b & 1) == 1):
return gcd(a >> 1, b)
else:
# both a and b are even
return (gcd(a >> 1, b >> 1) << 1)
# a is odd, b is even
if ((~b & 1) == 1):
return gcd(a, b >> 1)
# reduce larger number
if (a > b):
return gcd((a - b) >> 1, b)
return gcd((b - a) >> 1, a)
# Driver code
a, b = 34, 17
print("Gcd of given numbers is ",
gcd(a, b))
# This code is contributed
# by Nikita Tiwari.
C#
// Recursive C# program to
// implement Stein's Algorithm
using System;
class GFG {
// Function to implement
// Stein's Algorithm
static int gcd(int a, int b)
{
if (a == b)
return a;
// GCD(0, b) == b;
// GCD(a, 0) == a,
// GCD(0, 0) == 0
if (a == 0)
return b;
if (b == 0)
return a;
// look for factors of 2
// a is even
if ((~a & 1) == 1) {
// b is odd
if ((b & 1) == 1)
return gcd(a >> 1, b);
else
// both a and b are even
return gcd(a >> 1, b >> 1) << 1;
}
// a is odd, b is even
if ((~b & 1) == 1)
return gcd(a, b >> 1);
// reduce larger number
if (a > b)
return gcd((a - b) >> 1, b);
return gcd((b - a) >> 1, a);
}
// Driver code
public static void Main()
{
int a = 34, b = 17;
Console.Write("Gcd of given"
+ "numbers is " + gcd(a, b));
}
}
// This code is contributed by nitin mittal.
JavaScript
<script>
// JavaScript program to
// implement Stein's Algorithm
// Function to implement
// Stein's Algorithm
function gcd(a, b)
{
if (a == b)
return a;
// GCD(0, b) == b; GCD(a, 0) == a,
// GCD(0, 0) == 0
if (a == 0)
return b;
if (b == 0)
return a;
// look for factors of 2
if ((~a & 1) == 1) // a is even
{
if ((b & 1) == 1) // b is odd
return gcd(a >> 1, b);
else // both a and b are even
return gcd(a >> 1, b >> 1) << 1;
}
// a is odd, b is even
if ((~b & 1) == 1)
return gcd(a, b >> 1);
// reduce larger number
if (a > b)
return gcd((a - b) >> 1, b);
return gcd((b - a) >> 1, a);
}
// Driver Code
let a = 34, b = 17;
document.write("Gcd of given "
+ "numbers is " + gcd(a, b));
</script>
PHP
<?php
// Recursive PHP program to
// implement Stein's Algorithm
// Function to implement
// Stein's Algorithm
function gcd($a, $b)
{
if ($a == $b)
return $a;
/* GCD(0, b) == b; GCD(a, 0) == a,
GCD(0, 0) == 0 */
if ($a == 0)
return $b;
if ($b == 0)
return $a;
// look for factors of 2
if (~$a & 1) // a is even
{
if ($b & 1) // b is odd
return gcd($a >> 1, $b);
else // both a and b are even
return gcd($a >> 1, $b >> 1) << 1;
}
if (~$b & 1) // a is odd, b is even
return gcd($a, $b >> 1);
// reduce larger number
if ($a > $b)
return gcd(($a - $b) >> 1, $b);
return gcd(($b - $a) >> 1, $a);
}
// Driver code
$a = 34; $b = 17;
echo "Gcd of given numbers is: ",
gcd($a, $b);
// This code is contributed by aj_36
?>
OutputGcd of given numbers is 17
Time Complexity: O(N*N) where N is the number of bits in the larger number.
Auxiliary Space: O(N*N) where N is the number of bits in the larger number.
You may also like - Basic and Extended Euclidean Algorithm
Advantages over Euclid's GCD Algorithm
- Stein's algorithm is optimized version of Euclid's GCD Algorithm.
- it is more efficient by using the bitwise shift operator.
Similar Reads
LCM of given array elements In this article, we will learn how to find the LCM of given array elements.Given an array of n numbers, find the LCM of it. Example:Input : {1, 2, 8, 3}Output : 24LCM of 1, 2, 8 and 3 is 24Input : {2, 7, 3, 9, 4}Output : 252Table of Content[Naive Approach] Iterative LCM Calculation - O(n * log(min(a
14 min read
GCD of more than two (or array) numbers Given an array arr[] of non-negative numbers, the task is to find GCD of all the array elements. In a previous post we find GCD of two number.Examples:Input: arr[] = [1, 2, 3]Output: 1Input: arr[] = [2, 4, 6, 8]Output: 2Using Recursive GCDThe GCD of three or more numbers equals the product of the pr
11 min read
Euler's Totient Function Euler's Totient function Φ(n) for an input n is the count of numbers in {1, 2, 3, ..., n-1} that are relatively prime to n, i.e., the numbers whose GCD (Greatest Common Divisor) with n is 1. If n is a positive integer and its prime factorization is; n = p_1^{e_1} \cdot p_2^{e_2} \cdot \ldots \cdot p
15+ min read
Euclidean algorithms (Basic and Extended) The Euclidean algorithm is a way to find the greatest common divisor of two positive integers. GCD of two numbers is the largest number that divides both of them. A simple way to find GCD is to factorize both numbers and multiply common prime factors.Examples:input: a = 12, b = 20Output: 4Explanatio
9 min read
Stein's Algorithm for finding GCD Stein's algorithm or binary GCD algorithm is an algorithm that computes the greatest common divisor of two non-negative integers. Steinâs algorithm replaces division with arithmetic shifts, comparisons, and subtraction.Examples: Input: a = 17, b = 34 Output : 17Input: a = 50, b = 49Output: 1Algorith
14 min read
Program to find LCM of two numbers LCM of two numbers is the smallest number which can be divided by both numbers. Input : a = 12, b = 18Output : 3636 is the smallest number divisible by both 12 and 18Input : a = 5, b = 11Output : 5555 is the smallest number divisible by both 5 and 11[Naive Approach] Using Conditional Loop This appro
8 min read
GCD, LCM and Distributive Property Given three integers x, y, z, the task is to compute the value of GCD(LCM(x,y), LCM(x,z)) where, GCD = Greatest Common Divisor, LCM = Least Common MultipleExamples: Input: x = 15, y = 20, z = 100Output: 60Explanation: The GCD of 15 and 20 is 5, and the LCM of 15 and 20 is 60, which is then multiplie
4 min read
Euler's Totient function for all numbers smaller than or equal to n Euler's Totient function ?(n) for an input n is the count of numbers in {1, 2, 3, ..., n} that are relatively prime to n, i.e., the numbers whose GCD (Greatest Common Divisor) with n is 1. For example, ?(4) = 2, ?(3) = 2 and ?(5) = 4. There are 2 numbers smaller or equal to 4 that are relatively pri
13 min read
Count number of pairs (A <= N, B <= N) such that gcd (A , B) is B Given a number n, we need to find the number of ordered pairs of a and b such gcd(a, b) is b itselfExamples : Input : n = 2Output : 3The pairs are (1, 1) (2, 2) and (2, 1) Input : n = 3Output : 5(1, 1) (2, 2) (3, 3) (2, 1) and (3, 1)[Naive Approach] Counting GCD Pairs by Divisor Propertygcd(a, b) =
6 min read
Problems on GCD
Series with largest GCD and sum equals to nGiven an integer n, print m increasing numbers such that the sum of m numbers is equal to n and the GCD of m numbers is maximum among all series possible. If no series is possible then print â-1â.Examples : Input : n = 24, m = 3 Output : 4 8 12 Explanation : (4, 8, 12) has gcd = 4 which is the maxim
11 min read
Program to find GCD of floating point numbersThe greatest common divisor (GCD) of two or more numbers, which are not all zero, is the largest positive number that divides each of the numbers. Example: Input : 0.3, 0.9Output : 0.3Explanation: The GCD of 0.3 and 0.9 is 0.3 because both numbers share 0.3 as the largest common divisor.Input : 0.48
4 min read
Largest Subset with GCD 1Given n integers, we need to find size of the largest subset with GCD equal to 1. Input Constraint : n <= 10^5, A[i] <= 10^5Examples: Input : A = {2, 3, 5}Output : 3Explanation: The largest subset with a GCD greater than 1 is {2, 3, 5}, and the GCD of all the elements in the subset is 3.Input
6 min read
Summation of GCD of all the pairs up to nGiven a number n, find sum of all GCDs that can be formed by selecting all the pairs from 1 to n. Examples: Input : n = 4Output : 7Explanation: Numbers from 1 to 4 are: 1, 2, 3, 4Result = gcd(1,2) + gcd(1,3) + gcd(1,4) + gcd(2,3) + gcd(2,4) + gcd(3,4) = 1 + 1 + 1 + 1 + 2 + 1 = 7Input : n = 12Output
10 min read
GCD of more than two (or array) numbersGiven an array arr[] of non-negative numbers, the task is to find GCD of all the array elements. In a previous post we find GCD of two number.Examples:Input: arr[] = [1, 2, 3]Output: 1Input: arr[] = [2, 4, 6, 8]Output: 2Using Recursive GCDThe GCD of three or more numbers equals the product of the pr
11 min read
GCD of digits of a given numberGiven a number n, find GCD of its digits. Examples : Input : 345 Output : 1 GCD of 3, 4 and 5 is 1. Input : 2448 Output : 2 GCD of 2, 4, 4 and 8 is 2 We traverse the digits of number one by one using below loop digit = n mod 10; n = n / 10; While traversing digits, we keep track of current GCD and k
4 min read
Maximize GCD of all possible pairs from 1 to NGiven an integer N (> 2), the task is to find the maximum GCD among all pairs possible by the integers in the range [1, N]. Example: Input: N = 5 Output: 2 Explanation : GCD(1, 2) : 1 GCD(1, 3) : 1 GCD(1, 4) : 1 GCD(1, 5) : 1 GCD(2, 3) : 1 GCD(2, 4) : 2 GCD(2, 5) : 1 GCD(3, 4) : 1 GCD(3, 5) : 1 G
3 min read
GCD of two numbers formed by n repeating x and y timesGiven three positive integer n, x, y. The task is to print Greatest Common Divisor of numbers formed by n repeating x times and number formed by n repeating y times. 0 <= n, x, y <= 1000000000.Examples : Input : n = 123, x = 2, y = 3. Output : 123 Number formed are 123123 and 123123123. Greate
6 min read
Program to find Greatest Common Divisor (GCD) of N stringsGiven an array of string arr[], the task is the Greatest Common Divisor of the given array of string. In strings 'A' and 'B', we say "B divides A" if and only if A = concatenation of B more than 1 times.Find the largest string which divides both A and B. Examples: Input: arr[] = { "GFGGFG", "GFGGFG"
13 min read
Find the GCD that lies in given rangeGiven two positive integer a and b and a range [low, high]. The task is to find the greatest common divisor of a and b which lie in the given range. If no divisor exist in the range, print -1.Examples: Input : a = 9, b = 27, low = 1, high = 5 Output : 3 3 is the highest number that lies in range [1,
7 min read
Find the maximum GCD of the siblings of a Binary TreeGiven a 2d-array arr[][] which represents the nodes of a Binary tree, the task is to find the maximum GCD of the siblings of this tree without actually constructing it. Example:Â Â Input: arr[][] = {{4, 5}, {4, 2}, {2, 3}, {2, 1}, {3, 6}, {3, 12}}Â Output: 6Â Explanation:Â Â For the above tree, the maxi
11 min read