Finding a Non Transitive Coprime Triplet in a Range in C++

C++Server Side ProgrammingProgramming

C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

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
Updated on 21-Oct-2019 13:49:21