在 C++ 中找到一個範圍內的非傳遞互質三元組
假設我們有下界和上界,我們必須找到非傳遞三元組 (x, y, z),其中對 (x, y) 互質(最大公約數為 1),對 (y, z) 互質,但對 (x, z) 不是互質對。例如,如果下界為 2,上界為 10,那麼元素為 {2, 3, 4, 5, 6, 7, 8, 9, 10},此處的可能三元組為 (4, 7, 8),其中 (4, 7) 和 (7, 8) 互質,但 (4, 8) 不是互質對。
我們將採用樸素的方法來解決這個問題。我們將生成下界和上界範圍內的所有可能三元組,然後匹配條件。
示例
#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); }
輸出
(8, 9, 10) is one such possible triplet between 2 and 10
廣告