- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find any pair with given GCD and LCM in C++
In this section we will see how to get number of pairs using the given GCD and LCM values. Suppose the GCD and LCM values are 2 and 12. Now the possible pairs of numbers are (2, 12), (4, 6), (6, 4) and (12, 2). So our program will find the count of pairs. That is 4.
Let us see the algorithm to understand what will be the technique to solve this problem.
Algorithm
countPairs(gcd, lcm): Begin if lcm is nit divisible by gcd, then return 0 temp := lcm/gcd c := primeFactorCount(temp) res := shift 1 to the left c number of times return res End primeFactorCount(n): Begin count := 0 until n is not odd, increase count and divide n by 2 for i := 3, when i2 < n, increase i by 2, do if n is divisible by i, then increase count while n is divisible by i, do n := n / i done end if done if n > 2, then increase count by 1 return count End
Example
#include<iostream> #include<cmath> using namespace std; int primeFactorCount(int); int countPairs(int gcd, int lcm) { if(lcm % gcd != 0) return 0; int temp = lcm/gcd; return (1 << primeFactorCount(temp)); } int primeFactorCount(int n){ int count = 0; if(n%2 == 0){ //if n is divisible by 0, enter into the next part count++; while(n%2 == 0) n = n/2; } //now n is odd, so if we increase n by 2, all numbers will be odd for(int i = 3; i*i <= n; i = i + 2){ if(n%i == 0){ //if n is divisible by 0, enter into the next part count++; while(n%i == 0) n = n/i; } } if(n > 2) count++; return count; } int main() { cout << "Possible pairs of GCD = 2, and LCM = 12 is " <<countPairs(2, 12); }
Output
Possible pairs of GCD = 2, and LCM = 12 is 4
- Related Articles
- Find pair with maximum GCD in an array in C++
- Write a C# program to find GCD and LCM?
- C++ Program to Find the GCD and LCM of n Numbers
- Find original numbers from gcd() every pair in C++
- GCD and LCM of two numbers in Java
- Find the GCD of N Fibonacci Numbers with given Indices in C++
- Find a pair with the given difference in C++
- Minimum LCM and GCD possible among all possible sub-arrays in C++
- Find two numbers whose sum and GCD are given in C++
- Find a pair with given sum in BST in C++
- Find original numbers from gcd() every pair in Python
- Array with GCD of any of its subset belongs to the given array?
- Find pair with maximum difference in any column of a Matrix in C++
- Find the other number when LCM and HCF given in C++
- Queries to update a given index and find gcd in range in C++

Advertisements