在 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

更新时间:2019 年 10 月 21 日

71 次浏览

开启您的事业

完成课程从而获得认证

开始
广告
© . All rights reserved.