The Wayback Machine - https://web.archive.org/web/20240818215415/https://www.geeksforgeeks.org/steins-algorithm-for-finding-gcd/
Open In App

Stein’s Algorithm for finding GCD

Last Updated : 04 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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) 

  1. If both a and b are 0, gcd is zero gcd(0, 0) = 0.
  2. gcd(a, 0) = a and gcd(0, b) = b because everything divides 0.
  3. 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.
  4. 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.
  5. 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
  6. 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.

Iterative Implementation

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


Python3




# 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


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
?>


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>


Output

Gcd of given numbers is 17

Time Complexity: O(N*N)
Auxiliary Space: O(1)

Recursive Implementation

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


Python3




# 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.


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
?>


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>


Output

Gcd 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.



Previous Article
Next Article

Similar Reads

Finding LCM of more than two (or array) numbers without using GCD
Given an array of positive integers, find LCM of the elements present in array.Examples: Input : arr[] = {1, 2, 3, 4, 28} Output : 84 Input : arr[] = {4, 6, 12, 24, 30} Output : 120 We have discussed LCM of array using GCD.In this post a different approach is discussed that doesn't require computation of GCD. Below are steps. Initialize result = 1F
9 min read
Smallest subsequence having GCD equal to GCD of given array
Given an array arr[] of size N, the task is to find the smallest subsequence of the given array whose GCD of the subsequence is equal to the GCD of the given array. If more than one such subsequence exists, then print anyone of them. Examples: Input: arr[] = {4, 6, 12}Output: 4 6Explanation: Smallest subsequence having gcd equal to gcd of the given
7 min read
Pair of integers having least GCD among all given pairs having GCD exceeding K
Given an array arr[][] containing pairs of integers in increasing order of GCDs, and an integer K, the task is to find a pair of integers whose GCD is at least K and is also the least among all possible GCDs exceeding K. If there exists no such pair, then print -1.Examples: Input: arr[][] = [(3, 6), (15, 30), (25, 75), (30, 120)], K = 16 Output: (2
7 min read
Count all possible values of K less than Y such that GCD(X, Y) = GCD(X+K, Y)
Given two integers X and Y, the task is to find the number of integers, K, such that gcd(X, Y) is equal to gcd(X+K, Y), where 0 &lt; K &lt;Y. Examples: Input: X = 3, Y = 15Output: 4Explanation: All possible values of K are {0, 3, 6, 9} for which GCD(X, Y) = GCD(X + K, Y). Input: X = 2, Y = 12Output: 2Explanation: All possible values of K are {0, 8}
8 min read
Find N distinct integers with GCD of sequence as 1 and GCD of each pair greater than 1
Given an integer N, the task is to find a sequence of N distinct positive integers such that the Greatest Common Divisor of the sequence is 1 and GCD of all possible pairs of elements is greater than 1. Input: N = 4Output: 84 60 105 70Explanation: The GCD(84, 60, 105, 70) is 1 and the GCD of all possible pair of elements i.e, {(84, 60), (84, 105),
5 min read
Tomohiko Sakamoto's Algorithm- Finding the day of the week
Given any date according to the Gregorian Calendar, the task is to return the day(Monday, Tuesday...etc) on that particular day. Examples: Input : Date: 13 July 2017 [13.07.2017] Output : 4 i.e Thursday Input : Date: 15 August 2012 [15.08.2012] Output : 3 i.e Wednesday Input : Date: 24 December 2456 [24.12.2456] Output : 0 i.e Sunday Although there
6 min read
Floyd’s Cycle Finding Algorithm
Floyd's cycle finding algorithm or Hare-Tortoise algorithm is a pointer algorithm that uses only two pointers, moving through the sequence at different speeds. This algorithm is used to find a loop in a linked list. It uses two pointers one moving twice as fast as the other one. The faster one is called the fast pointer and the other one is called
14 min read
Finding optimal move in Tic-Tac-Toe using Minimax Algorithm in Game Theory
Prerequisites: Minimax Algorithm in Game Theory, Evaluation Function in Game TheoryLet us combine what we have learnt so far about minimax and evaluation function to write a proper Tic-Tac-Toe AI (Artificial Intelligence) that plays a perfect game. This AI will consider all possible scenarios and makes the most optimal move. Finding the Best Move :
15+ min read
Edge Relaxation Property for Dijkstra’s Algorithm and Bellman Ford's Algorithm
In the field of graph theory, various shortest path algorithms especially Dijkstra’s algorithm and Bellmann-Ford’s algorithm repeatedly employ the use of the technique called Edge Relaxation. The idea of relaxation is the same in both algorithms and it is by understanding, the 'Relaxation property' we can fully grasp the working of the two algorith
4 min read
Difference between Greedy Algorithm and Divide and Conquer Algorithm
Greedy algorithm and divide and conquer algorithm are two common algorithmic paradigms used to solve problems. The main difference between them lies in their approach to solving problems. Greedy Algorithm:The greedy algorithm is an algorithmic paradigm that follows the problem-solving heuristic of making the locally optimal choice at each stage wit
3 min read
Algorithm Library | C++ Magicians STL Algorithm
For all those who aspire to excel in competitive programming, only having a knowledge about containers of STL is of less use till one is not aware what all STL has to offer. STL has an ocean of algorithms, for all &lt; algorithm &gt; library functions : Refer here.Some of the most used algorithms on vectors and most useful one's in Competitive Prog
7 min read
What is the stupidest sorting algorithm? (Worst Sorting Algorithm)
Bogo sort stands out as the undisputed champion of stupidity. Unlike other sorting algorithms that follow a structured approach, Bogo sort relies on sheer luck and randomness to achieve its goal. How Bogo Sort Works?Bogo sort operates on the following principle: Randomly shuffle the elements in the list.Check if the list is sorted.If the list is no
2 min read
Difference Between Dijkstra's Algorithm and A* Search Algorithm
Dijkstra's Algorithm and A* Algorithm are two of the most widely used techniques. Both are employed to the find the shortest path between the nodes in a graph but they have distinct differences in their approaches and applications. Understanding these differences is crucial for the selecting the appropriate algorithm for the given problem. What is
3 min read
Z algorithm (Linear time pattern searching Algorithm)
This algorithm efficiently locates all instances of a specific pattern within a text in linear time. If the length of the text is "n" and the length of the pattern is "m," then the total time taken is O(m + n), with a linear auxiliary space. It is worth noting that the time and auxiliary space of this algorithm is the same as the KMP algorithm, but
13 min read
Karatsuba algorithm for fast multiplication using Divide and Conquer algorithm
Given two binary strings that represent value of two integers, find the product of two strings. For example, if the first bit string is "1100" and second bit string is "1010", output should be 120. For simplicity, let the length of two strings be same and be n. A Naive Approach is to follow the process we study in school. One by one take all bits o
15+ min read
Finding Bitwise AND sum paths in Binary trees
Given a binary tree and a target sum, determine whether there exists a root-to-leaf path in the tree such that the sum of the values of the nodes along the path is equal to the target sum when represented in binary, and the sum of the values of the nodes along the path is calculated by performing a bitwise AND operation between the binary represent
11 min read
Finding nth term of any Polynomial Sequence
Given a few terms of a sequence, we are often asked to find the expression for the nth term of this sequence. While there is a multitude of ways to do this, In this article, we discuss an algorithmic approach which will give the correct answer for any polynomial expression. Note that this method fails for trigonometric, exponential or other transce
4 min read
Finding a Non Transitive Co-prime Triplet in a Range
Given L and R, find a possible non-transitive triplet (a, b, c) such that pair (a, b) is co-prime and pair (b, c) is co-prime but (a, c) is not co-prime. Eg: (2, 5, 6) is a non-transitive triplet as pair (2, 5) is co-prime and pair (5, 6) is co-prime but pair (2, 6) is not co-prime. Examples: Input : L = 2, R = 10 Output : a = 4, b = 7, c = 8 is on
15+ min read
Finding n-th term of series 3, 13, 42, 108, 235â€Ķ
Given a number n, find the n-th term in the series 3, 13, 42, 108, 235â€ĶExamples: Input : 3 Output : 42 Input : 4 Output : 108 Constraints: 1 &lt;= T &lt;= 100 1 &lt;= N &lt;= 100Naive Approach : The series basically represents sums of natural numbers cube and number of terms multiplied by 2. The first term is the sum of the single number. The secon
6 min read
Finding Quadrant of a Coordinate with respect to a Circle
Given the radius and coordinates of the Centre of a circle. Find the quadrant in which another given coordinate (X, Y) lies with respect to the Centre of the circle if the point lies inside the circle. Else print an error "Lies outside the circle". If the point lies at the Centre of circle output 0 or if the point lies on any of the axes and inside
8 min read
Finding Floor and Ceil of a Sorted Array using C++ STL
Given a sorted array, the task is to find the floor and ceil of given numbers using STL.Examples: Input: arr[] = {1, 2, 4, 7, 11, 12, 23, 30, 32}, values[] = { 1, 3, 5, 7, 20, 24 } Output: Floor Values: 1 2 4 7 12 23 Ceil values: 1 4 7 7 23 30 In case of floor(): lower_bound() method os STL will be used to find the lower bound. This returns an iter
3 min read
Finding the Parity of a number Efficiently
Given an integer N. The task is to write a program to find the parity of the given number. Note: Parity of a number is used to define if the total number of set-bits(1-bit in binary representation) in a number is even or odd. If the total number of set-bits in the binary representation of a number is even then the number is said to have even parity
8 min read
Finding the probability of a state at a given time in a Markov chain | Set 2
Given a Markov chain G, we have the find the probability of reaching the state F at time t = T if we start from state S at time t = 0.A Markov chain is a random process consisting of various states and the probabilities of moving from one state to another. We can represent it using a directed graph where the nodes represent the states and the edges
11 min read
Finding in and out degrees of all vertices in a graph
Given a directed graph, the task is to count the in and out degree of each vertex of the graph. Examples: Input: Output: Vertex In Out 0 1 2 1 2 1 2 2 3 3 2 2 4 2 2 5 2 2 6 2 1 Approach: Traverse adjacency list for every vertex, if size of the adjacency list of vertex i is x then the out degree for i = x and increment the in degree of every vertex
9 min read
Finding the converging element of the diagonals in a square matrix
Given a square matrix, the task is to find the element of the matrix where the right and the left diagonal of this square matrix converge.Example: Input: n = 5, matrix = [ 1 2 3 4 5 5 6 7 8 6 9 5 6 8 7 2 3 5 6 8 1 2 3 4 5 ] Output: 6 Input: n = 4, matrix = [ 1 2 3 4 5 6 7 8 9 0 1 2 4 5 6 1 ] Output: NULL Here there no converging element at all. Hen
4 min read
Finding if a node X is present in subtree of another node Y or vice versa for Q queries
Given a tree with N nodes and (N-1) edges and source node is at 1st position. There are Q queries, each of the type {pos, X, Y}. Perform the following operation based on the type of the query: If pos = 0, then find if Y is present in the subtree of X.If pos = 1, then find if X is present in the subtree of Y. Examples: Input: N: = 9, edges = {{1, 2}
12 min read
Find intersection point of two Linked Lists without finding the length
There are two singly linked lists in a system. By some programming error, the end node of one of the linked lists got linked to the second list, forming an inverted Y shaped list. Write a program to get the point where both the linked lists merge. Examples: Input: 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; 6 ^ | 7 -&gt; 8 -&gt; 9 Output: 4 Input: 13 -
7 min read
Finding powers of any number P in N!
Prerequisite: Print all prime factors and their powers Given natural numbers N and P, the task is to find the power of P in the factorization of N!. Examples Input: N = 4, P = 2 Output: 3 Explanation: Power of 2 in the prime factorization of 4! = 24 is 3 Input: N = 24, P = 4 Output: 11 Naive Approach: The idea is to find the power of P for each num
11 min read
Finding Integrand using Weedle's Rule
Given a function [Tex]f(x) [/Tex]and two integers a and b. The task is to find the integrand of the given function from lower limit(a) to the upper limit(b) using Weedle's Rule. The given function is: [Tex]f(x) = \frac{1}{(1+x)^2} [/Tex] Examples: Input: a = 0, b = 6 Output: 1.373448 Input: a = 10, b = 13 Output: f(x) = 0.022897 Approach: The integ
7 min read
Program for finding the Integral of a given function using Boole's Rule
Given a function, f(x), tabulated at points [Tex]x_i [/Tex] equally spaced by [Tex]h=x_{i+1} - x_i [/Tex] such that [Tex]f_1 = f(x_1) [/Tex][Tex]f_2=f(x_2)[/Tex] .....and so on The upper and lower limits a, b correspond to which the integral needs to be found, the task is to find the integral value of the given equation f(x).Examples: Input: a = 0,
9 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg