Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Count pairs of natural numbers with GCD equal to given number
Next article icon

Count pairs of natural numbers with GCD equal to given number

Last Updated : 12 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given three positive integer L, R, G. The task is to find the count of the pair (x,y) having GCD(x,y) = G and x, y lie between L and R.
Examples: 
 

Input : L = 1, R = 11, G = 5  Output : 3  (5, 5), (5, 10), (10, 5) are three pair having GCD equal to 5 and lie between 1 and 11.  So answer is 3.    Input : L = 1, R = 10, G = 7  Output : 1


 


A simple solution is to go through all pairs in [L, R]. For every pair, find its GCD. If GCD is equal to g, then increment count. Finally return count.
An efficient solution is based on the fact that, for any positive integer pair (x, y) to have GCD equal to g, x and y should be divisible by g. 
Observe, there will be at most (R - L)/g numbers between L and R which are divisible by g. 
So we find numbers between L and R which are divisible by g. For this, we start from ceil(L/g) * g and with increment by g at each step while it doesn't exceed R, count numbers having GCD equal to 1. 
Also, 

ceil(L/g) * g = floor((L + g - 1) / g) * g.


Below is the implementation of above idea : 
 

C++
// C++ program to count pair in range of natural // number having GCD equal to given number. #include <bits/stdc++.h> using namespace std;  // Return the GCD of two numbers. int gcd(int a, int b) {     return b ? gcd(b, a % b) : a; }  // Return the count of pairs having GCD equal to g. int countGCD(int L, int R, int g) {     // Setting the value of L, R.     L = (L + g - 1) / g;     R = R/ g;      // For each possible pair check if GCD is 1.     int ans = 0;     for (int i = L; i <= R; i++)         for (int j = L; j <= R; j++)             if (gcd(i, j) == 1)                 ans++;      return ans; }  // Driven Program int main() {     int L = 1, R = 11, g = 5;     cout << countGCD(L, R, g) << endl;     return 0; } 
Java
// Java program to count pair in  // range of natural number having  // GCD equal to given number. import java.util.*;  class GFG {      // Return the GCD of two numbers. static int gcd(int a, int b)  {     return b > 0 ? gcd(b, a % b) : a;  }  // Return the count of pairs // having GCD equal to g. static int countGCD(int L, int R, int g) {          // Setting the value of L, R.     L = (L + g - 1) / g;     R = R / g;      // For each possible pair check if GCD is 1.     int ans = 0;     for (int i = L; i <= R; i++)     for (int j = L; j <= R; j++)         if (gcd(i, j) == 1)         ans++;      return ans; }  // Driver code public static void main(String[] args) {          int L = 1, R = 11, g = 5;     System.out.println(countGCD(L, R, g)); } }  // This code is contributed by Anant Agarwal. 
Python3
# Python program to count # pair in range of natural # number having GCD equal # to given number.  # Return the GCD of two numbers. def gcd(a,b):      return gcd(b, a % b) if b>0 else a    # Return the count of pairs # having GCD equal to g. def countGCD(L,R,g):      # Setting the value of L, R.     L = (L + g - 1) // g     R = R// g       # For each possible pair     # check if GCD is 1.     ans = 0     for i in range(L,R+1):         for j in range(L,R+1):             if (gcd(i, j) == 1):                 ans=ans +1       return ans  # Driver code  L = 1 R = 11 g = 5  print(countGCD(L, R, g))  # This code is contributed # by Anant Agarwal. 
C#
// C# program to count pair in  // range of natural number having  // GCD equal to given number. using System;  class GFG {      // Return the GCD of two numbers. static int gcd(int a, int b)  {     return b > 0 ? gcd(b, a % b) : a;  }  // Return the count of pairs // having GCD equal to g. static int countGCD(int L, int R,                     int g) {          // Setting the value of L, R.     L = (L + g - 1) / g;     R = R / g;      // For each possible pair      // check if GCD is 1.     int ans = 0;     for (int i = L; i <= R; i++)     for (int j = L; j <= R; j++)         if (gcd(i, j) == 1)         ans++;      return ans; }  // Driver code public static void Main()  {          int L = 1, R = 11, g = 5;     Console.WriteLine(countGCD(L, R, g)); } }  // This code is contributed by vt_m. 
PHP
<?php // PHP program to count pair // in range of natural number // having GCD equal to given number.  // Return the GCD of two numbers. function gcd( $a, $b) {     return $b ? gcd($b, $a % $b) : $a; }  // Return the count of pairs  // having GCD equal to g. function countGCD( $L, $R, $g) {          // Setting the value of L, R.     $L = ($L + $g - 1) / $g;     $R = $R/ $g;      // For each possible pair     // check if GCD is 1.     $ans = 0;     for($i = $L; $i <= $R; $i++)         for($j = $L; $j <= $R; $j++)             if (gcd($i, $j) == 1)                 $ans++;      return $ans; }      // Driver Code     $L = 1;      $R = 11;     $g = 5;     echo countGCD($L, $R, $g);  // This code is contributed by anuj_67. ?> 
JavaScript
<script>     // Javascript program to count pair in      // range of natural number having      // GCD equal to given number.          // Return the GCD of two numbers.     function gcd(a, b)      {         return b > 0 ? gcd(b, a % b) : a;      }      // Return the count of pairs     // having GCD equal to g.     function countGCD(L, R, g)     {          // Setting the value of L, R.         L = parseInt((L + g - 1) / g, 10);         R = parseInt(R / g, 10);          // For each possible pair          // check if GCD is 1.         let ans = 0;         for (let i = L; i <= R; i++)         for (let j = L; j <= R; j++)             if (gcd(i, j) == 1)             ans++;          return ans;     }          let L = 1, R = 11, g = 5;     document.write(countGCD(L, R, g));      </script> 

Output: 
 

3

Time Complexity : O((r-l)*(r-l)*log(min(k))) where l and r are lower limit, upper limit and k is the number between l and r.

Space Complexity : O(logk)

 


Next Article
Count pairs of natural numbers with GCD equal to given number

K

kartik
Improve
Article Tags :
  • Mathematical
  • DSA
  • GCD-LCM
Practice Tags :
  • Mathematical

Similar Reads

    GCD (Greatest Common Divisor) Practice Problems for Competitive Programming
    GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest positive integer that divides both of the numbers.GCD of Two NumbersFastest Way to Compute GCDThe fastest way to find the Greatest Common Divisor (GCD) of two numbers is by using the Euclidean algorithm. The E
    4 min read
    Program to Find GCD or HCF of Two Numbers
    Given two positive integers a and b, the task is to find the GCD of the two numbers.Note: The GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest number that divides both of them. Examples:Input: a = 20, b = 28Output: 4Explanation: The factors of 20 are 1, 2, 4
    12 min read
    Check if two numbers are co-prime or not
    Two numbers A and B are said to be Co-Prime or mutually prime if the Greatest Common Divisor of them is 1. You have been given two numbers A and B, find if they are Co-prime or not.Examples : Input : 2 3Output : Co-PrimeInput : 4 8Output : Not Co-PrimeThe idea is simple, we find GCD of two numbers a
    5 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
    Program to find LCM of two numbers
    Given two positive integers a and b. Find the Least Common Multiple (LCM) of a and b.LCM of two numbers is the smallest number which can be divided by both numbers. Input : a = 10, b = 5Output : 10Explanation : 10 is the smallest number divisible by both 10 and 5Input : a = 5, b = 11Output : 55Expla
    5 min read
    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
    Find the other number when LCM and HCF given
    Given a number A and L.C.M and H.C.F. The task is to determine the other number B. Examples: Input: A = 10, Lcm = 10, Hcf = 50. Output: B = 50 Input: A = 5, Lcm = 25, Hcf = 4. Output: B = 20 Formula: A * B = LCM * HCF B = (LCM * HCF)/AExample : A = 15, B = 12 HCF = 3, LCM = 60 We can see that 3 * 60
    4 min read
    Minimum insertions to make a Co-prime array
    Given an array of N elements, find the minimum number of insertions to convert the given array into a co-prime array. Print the resultant array also.Co-prime Array : An array in which every pair of adjacent elements are co-primes. i.e, gcd(a, b) = 1 . Examples : Input : A[] = {2, 7, 28}Output : 1Exp
    6 min read
    Find the minimum possible health of the winning player
    Given an array health[] where health[i] is the health of the ith player in a game, any player can attack any other player in the game. The health of the player being attacked will be reduced by the amount of health the attacking player has. The task is to find the minimum possible health of the winn
    4 min read
    Minimum squares to evenly cut a rectangle
    Given a rectangular sheet of length l and width w. we need to divide this sheet into square sheets such that the number of square sheets should be as minimum as possible.Examples: Input :l= 4 w=6 Output :6 We can form squares with side of 1 unit, But the number of squares will be 24, this is not min
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences