The Wayback Machine - https://web.archive.org/web/20240925112745/https://www.geeksforgeeks.org/gcd-greatest-common-divisor-practice-problems-for-competitive-programming/
Open In App

GCD (Greatest Common Divisor) Practice Problems for Competitive Programming

Last Updated : 10 Nov, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest positive integer that divides both of the numbers.

GCD (Greatest Common Divisor)

Fastest way to compute GCD

The fastest way to find the Greatest Common Divisor (GCD) of two numbers is by using the Euclidean algorithm. The Euclidean algorithm is an efficient and widely used method for GCD calculation. It used to compute GCD of two numbers in O(log(min(a,b)).

It uses recursion to repeatedly replace a with b and b with the remainder of a divided by b until b becomes zero, returning a as the GCD. This approach is concise and efficient for GCD calculation.

Below is the code snippet for above algorithm:

C++




int gcd (int a, int b) {
    if (b == 0)
        return a;
    else
        return gcd (b, a % b);
}


Java




public static int gcd(int a, int b) {
    if (b == 0)
        return a;
    else
        return gcd(b, a % b);
}


Python3




def gcd(a, b):
    if b == 0:
        return a
    else:
        return gcd(b, a % b)


C#




using System;
 
int Gcd(int a, int b)
{
    if (b == 0)
        return a;
    else
        return Gcd(b, a % b);
}


Javascript




function gcd(a, b) {
    if (b === 0) {
        return a;
    } else {
        return gcd(b, a % b);
    }
}


Problems identification that involve GCD (Greatest Common Divisor)

GCD (Greatest Common Divisor) problems can vary in complexity and application, but they generally involve finding the greatest common divisor of one or more integers or applying GCD properties to solve a specific problem. Here are some common types of problems that involve GCD:

  • Problems that require to determine if one number is divisible by another may involve GCD, as GCD is related to the greatest common factor of two numbers.
  • Many number theory problems which related to coprime numbers, relatively prime numbers, or Euler’s totient function, involve GCD calculation.
  • Consider whether the problem hints about the need to factorize numbers into their prime factors. GCD problems sometimes involve prime factorization to find common factors efficiently.
  • In graph theory, GCD can be used in problems related to connected components, in which a edge between the nodes will only exist if they are not co-prime.

Here is a list of the Top GCD Problems for practice. Problems in this Article are divided into three Levels to practice according to the difficulty level step by step.

Easy Level Problems on GCD

Program to Find GCD or HCF of Two Numbers
Check if two numbers are co-prime or not
GCD of more than two (or array) numbers
Program to find LCM of two numbers
LCM of given array elements
Find the other number when LCM and HCF given
Minimum insertions to make a Co-prime array
Find the minimum possible health of the winning player
Minimum squares to evenly cut a rectangle
Minimum operations to make GCD of array a multiple of k

Medium Level Problems on GCD

LCM of First n Natural Numbers
Given GCD G and LCM L, find number of possible pairs (a, b)
Count numbers in range 1 to N which are divisible by X but not by Y
Minimum possible final health of the last monster in a game
Find the maximum GCD of the siblings of a Binary Tree
Check if possible to move from given coordinate to desired coordinate
Program to find Greatest Common Divisor (GCD) of N strings
Largest subsequence having GCD greater than 1
Subsequence of size k with maximum possible GCD
Minimum gcd operations to make all array elements one
GCD of elements in a given range
Count pairs of natural numbers with GCD equal to given number
Maximum GCD of all subarrays of length at least 2
Queries for GCD of all numbers of an array except elements in a given range
Minimum operations required to make two numbers equal
GCD of two numbers formed by n repeating x and y times

Hard Level Problems on GCD

Remove an element to maximize the GCD of the given array
Common divisors of N numbers
Find the number of pairs such that their gcd is equals to 1
Program to find Nth term divisible by a or b
Largest number that divides x and is co-prime with y
Summation of GCD of all the pairs up to N
Calculate the Sum of GCD over all subarrays
Sum of LCM(1, n), LCM(2, n), LCM(3, n), â€Ķ , LCM(n, n)
Count number of pairs (A <= N, B <= N) such that gcd (A , B) is B
Find original numbers from gcd() every pair
Count number of sub-sequences with GCD 1
Split array into minimum number of subarrays having GCD of its first and last element exceeding 1


Similar Reads

Program to find Greatest Common Divisor (GCD) of N strings
Given 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", "GFGGFGGFGGFG" } Output: "GFGGFG" Explanation: "
13 min read
Sum of greatest odd divisor of numbers in given range
Given an interval of integers [A, B]. For each number in this interval compute its greatest odd divisor. Output the sum of these divisors. Examples: Input : A = 1, B = 3 Output : 5 1 + 1 + 3 = 5 Input : A = 3, B = 9 Output : 29 3 + 1 + 5 + 3 + 7 + 1 + 9 = 29 Naive Approach :A simple approach is to iterate through all numbers in the range find their
7 min read
Queries on XOR of greatest odd divisor of the range
Given an array of N positive integers. There are Q queries, each include a range [L, R]. For each query output the xor of greatest odd divisor of each number in that range. Examples: Input : arr[] = { 3, 4, 5 } query 1: [0, 2] query 2: [1, 2] Output : 7 4 Greatest odd divisor are: { 3, 1, 5 } XOR of 3, 1, 5 is 7 XOR of 1, 5 is 4 Input : arr[] = { 2
5 min read
Tips and Tricks for Competitive Programmers | Set 2 (Language to be used for Competitive Programming)
This is a question asked quite often as in which language should be preferred to be efficient in competitive programming. It is something one should not worry about as what matters is the logic, not the language. Most of the languages are more or less same, but till now the most preferred language is C++, and here are the reasons. Python Simple and
5 min read
What are Ad Hoc Problems in Competitive Programming?
The Ad Hoc problems are problems that cannot be classified anywhere else in the categories with well-studied solutions since each problem description and its corresponding solution are unique. These problems don't fall under standard categories, there is no specific or general technique exists to solve them. Many Ad Hoc problems are easy, but this
5 min read
Interactive Problems in Competitive Programming | Set 2
Introduction to interactive problems in competitive programming is already discussed in the previous article. In this article, another problem based on the same concept is discussed. Assume that the judge has a hidden (it means the user can't access it) sorted array. The user (i.e. you) need to tell whether a given element VAL lies in that sorted a
3 min read
Mastering Bracket Problems for Competitive Programming
Bracket problems in programming typically refer to problems that involve working with parentheses, and/or braces in expressions or sequences. It typically refers to problems related to the correct and balanced usage of parentheses, and braces in expressions or code. These problems often involve checking if a given sequence of these symbols is well-
4 min read
Interactive Problems in Competitive Programming
Interactive Problems are those problems in which our solution or code interacts with the judge in real time. When we develop a solution for an Interactive Problem then the input data given to our solution may not be predetermined but is built for that problem specifically. The solution performs a series of exchange of data with the judge and at the
6 min read
Smallest divisor D of N such that gcd(D, M) is greater than 1
Given two positive integers N and M., The task is to find the smallest divisor D of N such that gcd(D, M) > 1. If there are no such divisors, then print -1. Examples: Input: N = 8, M = 10 Output: 2Input: N = 8, M = 1 Output: -1 A naive approach is to iterate for every factor and calculate the gcd of the factor and M. If it exceeds M, then we hav
6 min read
Common mistakes to be avoided in Competitive Programming in C++ | Beginners
Not using of 1LL or 1ll when needed // A program shows problem if we // don't use 1ll or 1LL #include <iostream> using namespace std; int main() { int x = 1000000; int y = 1000000; // This causes overflow even // if z is long long int long long int z = x*y; cout << z; return 0; } Output: -727379968 You might get some other negative valu
7 min read
Common Divisor Reduction Algorithm
Given two integers x and y. In one step, we have to subtract the greatest common divisor of x and y from x and y each till x â‰Ĩ 1 and y â‰Ĩ 1. We have to find the minimum number of repetitions of this step. Examples: Input: x = 36, y = 16Output: 4Explanation: GCD of 36 and 16 is 4, so replace 36 and 16 with 32 and 12GCD of 32 and 12 is 4, so replace 3
11 min read
Competitive Programming vs General Programming
Programming enthusiasts face a crossroads - Competitive Programming or General Programming? This article sheds light on the distinctions between Competitive Programming vs General Programming, offering a quick guide for those navigating the coding landscape. Whether you're aiming for speed and precision in competitions or tackling real-world projec
3 min read
Dynamic Programming in Game Theory for Competitive Programming
In the fast-paced world of competitive programming, mastering dynamic programming in game theory is the key to solving complex strategic challenges. This article explores how dynamic programming in game theory can enhance your problem-solving skills and strategic insights, giving you a competitive edge. Whether you're a seasoned coder or a newcomer
15+ min read
Optimal Strategy for the Divisor game using Dynamic Programming
Given an integer N and two players, A and B are playing a game. On each player’s turn, that player makes a move by subtracting a divisor of current N (which is less than N) from current N, thus forming a new N for the next turn. The player who does not have any divisor left to subtract loses the game. The task is to tell which player wins the game
9 min read
Can ChatGPT be used to solve Competitive Coding Problems?
For a very long time, human programmers have been the only ones allowed to compete in competitive coding, where they use their analytical thinking, coding knowledge, and problem-solving abilities to take on challenging tasks. However, the intriguing question of whether ChatGPT can be used to resolve challenging coding problems has arisen with the d
4 min read
GCD & LCM Coding Problems
Greatest Common Divisor (GCD): The GCD of two numbers is defined as the largest integer that divides both integers without any remainder. It is also termed as the HCF (Highest Common Factor). GCD of an array is the integer that divides all the elements of the array without leaving any remainder. GCD of two numbers may be calculated using the follow
3 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 < K <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
Practice Problems on Hashing
In this article, we will discuss the types of questions based on hashing. Before understanding this, you should have idea about hashing, hash function, open addressing and chaining techniques (see: Introduction, Separate chaining, Open addressing). These are some key points in hashing: The purpose of hashing is to achieve search, insert and delete
8 min read
Practice Problems on Game Theory
Game Theory is a topic in competitive programming that involves a certain type of problem, where there are some players who play a game based on given rules and the task is often to find the winner or the winning moves. Game Theory is often asked in short contests with a mixture of other topics like range querying or greedy or dynamic programming.
4 min read
Recursive Practice Problems with Solutions
Basics - Recursion Recursive Functions Tail Recursion Strings - Given a string, print all possible palindromic partitions Check if a number is Palindrome Print all possible strings of length k that can be formed from a set of n characters Recursive Implementation of atoi() Find all even length binary sequences with same sum of first and second half
4 min read
Sample Practice Problems on Complexity Analysis of Algorithms
Prerequisite: Asymptotic Analysis, Worst, Average and Best Cases, Asymptotic Notations, Analysis of loops. Problem 1: Find the complexity of the below recurrence: { 3T(n-1), if n>0,T(n) = { 1, otherwise Solution: Let us solve using substitution. T(n) = 3T(n-1) = 3(3T(n-2)) = 32T(n-2) = 33T(n-3) ... ... = 3nT(n-n) = 3nT(0) = 3n This clearly shows
15 min read
Bitwise Algorithms - Basic Practice Problems
Bitwise algorithms are a category of algorithms that operate on individual bits within a data unit, rather than the entire data unit itself. They leverage bitwise operators, which are special operators designed to perform operations on bits. Common bitwise operators include AND (&), OR (|), XOR (^), and NOT (~). Before diving into the world of
5 min read
Bitwise Algorithms - Intermediate Practice Problems
Bitwise operations are fundamental to computer programming and problem-solving. At the intermediate level, you'll explore more complex bitwise algorithms and techniques to solve a variety of coding challenges. This includes topics like bit manipulation, number theory, and optimization using bitwise operations. The practice problems will cover a ran
7 min read
How to read Competitive Programming Questions?
Competitive Programming is considered as a sport in the field of computer science. The culture of this sport is growing day by day and a lot of people are also considering this as a career choice. So, to help the participants with improving their efficiency in this sport, in this post, we have tried to cover all possible things, needed to keep in m
5 min read
Some useful C++ tricks for beginners in Competitive Programming
Here are some of the basic C++ tricks that every beginner in Competitive Programming should follow for increased speed. However, competitive programming can only be mastered with time and lots of practice. These tricks will just help you to save a little time during the contests which sometimes matters a lot. Using the auto keyword to declare data
3 min read
Importance of Testing In Competitive Programming
Many times while solving problems, we face issues like time limit exceeds, wrong solution, runtime error, and memory limit exceeds because after designing algorithm we don't test algorithm efficiency, correctness, time complexity and running the algorithm on a large set of inputs for testing purpose. This is where stress testing comes for rescue. S
3 min read
Writing code faster during Competitive Programming in C++
This article focuses on how to implement your solutions and implement them fast while doing competitive programming. Setup Please refer Setting up a C++ Competitive Programming Environment Snippets Snippet is a programming term for a small region of re-usable source Code. A lot of modern text editors like Sublime provide you a functionality to auto
3 min read
Article Tags :
Practice Tags :