使用 C++ 找出满足方程的六元组数

在本文中,我们将描述一种方法来找到满足方程的多个六胞胎。所以我们以一个方程为例,我们需要找到满足以下方程的 a、b、c、d、e 和 f 的值。

( a + b + c ) * e / d = f

让我们重新排列方程 -

( a + b + c ) = ( f * d ) / e

这是给定问题的一个简单示例 -

Input : arr [ ] = { 1, 3 }
Output : 4
Explanation : ( a, b, c, e, f ) = 1, d = 3
   ( a, b, c, d, e ) = 1, f = 3
   ( a, b, c ) = 1, ( d, e, f ) = 3
   ( a, b, c, d, f ) = 3, ( e ) = 1

Input : arr [ ] = { 2, 5 }
Output : 3

寻找解决方案的方法

我们将使用朴素的方法来找到给定问题的解决方案。

天真的方法

在这个问题中,查看LHS和RHS,我们可以找到LHS的所有可能结果并存储在一个数组中,类似地为RHS创建一个数组并用RHS的所有可能结果填充它。

检查两个数组是否有相同的值,并为找到的每个值增加计数,最后显示结果。

示例

#include<bits/stdc++.h>
using namespace std;
int findsamenumbers(int *arr1, int *arr2, int n){
    int i = 0, j = 0, k = 0, count=0;
    while(( i < n*n*n+1) && (j < n*n*n+1)){
        if(arr1[i] < arr2[j])
            i++;
        else if(arr1[i] == arr2[j]){
            count++;
        int temp = arr1[i];
        while(temp==arr1[++i]){
            count++;
        }
        while(temp==arr2[++j]){
            count++;
        }
    }
    else
        j++;
    }  
    return count;
}
int main(){
    int arr[] = {2,5};
    int n = sizeof(arr)/sizeof(arr[0]);
    // 生成 LHS 数组的所有可能值
    int index = 0,i;
    int LHS[n*n*n ];
    for ( i = 0; i < n; i++){
        for (int j = 0; j < n; j++){
            for(int k = 0; k < n; k++){
                LHS[index++] = (arr[i] * arr[j]) / arr[k];
            }
        }
    }
    // 生成 RHS 数组的所有可能值
    int RHS[n*n*n ];
    index=0;
    for (int i = 0; i < n; i++){
        for (int j = 0; j < n; j++){
            for (int k = 0; k < n; k++){
                RHS[index++] = (arr[i] + arr[j] + arr[k]);
            }
        }
    }
    sort(RHS, RHS + (n*n*n));
    sort(LHS, LHS + (n*n*n));
    int result = findsamenumbers(LHS, RHS, n);
    cout<<"满足方程的六胞胎数: "<<result;
    return 0;
}
输出结果
满足方程的六胞胎数: 3

以上程序说明

在这个程序中,我们创建了两个数组来保存 LHS 和 RHS 的每个结果。我们使用三个嵌套循环将 (a, b, c) 的每个可能值放在 LHS 中,将 (d, e, f) 放在 RHS 中。之后,我们对两个数组进行排序以比较两个数组并在两个数组中找到相同的值,将两个数组传递给findsamenumber()函数。

在findsamenumber()函数中,我们使用两个嵌套循环检查相同的值。当我们发现两个相同的元素时,我们检查该数字在两个数组中的频率,以便每个可能的值都计数。

if(arr1[i] == arr2[j]){
   count++;
   int temp = arr1[i];
   while(temp==arr1[++i]){
      count++;
   }
   while(temp==arr2[++j]){
      count++;
   }

结论

在本文中,我们求解了满足方程的六元组的数量,其中给定数组。我们在 6 个变量方程 (a + b + c) * e / d = f 中找到了变量的所有可能值。我们可以使用任何其他编程语言(如 C、Java 和 Python)来解决这个问题。