
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding a Non Transitive Coprime Triplet in a Range in C++
Suppose we have the lower and upper bound, and we have to find nontransitive triplet (x, y, z), such that the pair (x, y) are coprime (GCD is 1), the pair (y, z) are coprime, but pair (x, z) is not a coprime pair. For example, if the lower bound is 2, and upper bound is 10, then the elements are {2, 3, 4, 5, 6, 7, 8, 9, 10}, here possible triplet is (4, 7, 8), here (4, 7), and (7, 8) are coprime, but (4, 8) is not a coprime pair.
We will follow the naïve approach to solve this. We will generate all possible triplets in range lower bound and upper bound, then match the criteria.
Example
#include <iostream> #include <algorithm> using namespace std; bool isCoprime(int a, int b){ return (__gcd(a, b) == 1); } void tripletInRange(int left, int right) { bool flag = false; int A, B, C; // Generate and check for all possible triplets // between L and R for (int a = left; a <= right; a++) { for (int b = a + 1; b <= right; b++) { for (int c = b + 1; c <= right; c++) { if (isCoprime(a, b) && isCoprime(b, c) && ! isCoprime(a, c)) { flag = true; A = a; B = b; C = c; break; } } } } if (flag == true) { cout << "(" << A << ", " << B << ", " << C << ")" << " is one such possible triplet between " << left << " and " << right << endl; } else { cout << "No Such Triplet exists between " << left << " and " << right << endl; } } int main() { int left = 2, right = 10; tripletInRange(left, right); }
Output
(8, 9, 10) is one such possible triplet between 2 and 10
- Related Questions & Answers
- Finding Armstrong numbers in a given range in JavaScript
- Transitive closure of a Graph
- Finding sum of a range in an array JavaScript
- Finding sequential digit numbers within a range in JavaScript
- C++ Program to Find Transitive Closure of a Graph
- Finding sum of all numbers within a range in JavaScript
- Prime Triplet in C++
- Finding the first non-repeating character of a string in JavaScript
- Find a triplet that sum to a given value in C++
- How to store Data Triplet in a Vector in C++?
- Finding the k-prime numbers with a specific distance in a range in JavaScript
- Transitive dependency in DBMS
- Finding the simple non-isomorphic graphs with n vertices in a graph
- Search a value in JavaTuples Triplet class
- Finding the least common multiple of a range of numbers in JavaScript?
Advertisements