C++代码查找和为n的三个数


假设我们有一个数字n。我们要找到三个数字a、b和c,使得a + b + c = n,并且这三个数字都不是3的倍数。

因此,如果输入是n=233,那么输出将是[77、77、79]

步骤

为了解决这个问题,我们将按照以下步骤进行操作−

if (n - 2) mod 3 is same as 0, then:
   return 1, 2, and n - 3
Otherwise
   return 1, 1, and n - 2

示例

让我们看看以下实现,以便更好地理解−

#include <bits/stdc++.h>
using namespace std;
void solve(int n){
   if ((n - 2) % 3 == 0)
      cout << 1 << ", " << 2 << ", " << n - 3;
   else
      cout << 1 << ", " << 1 << ", " << n - 2;
}
int main(){
   int n = 233;
   solve(n);
}

输入

233

输出

1, 2, 230

更新于: 15-3-2022

322次浏览

开启你的职业生涯

完成课程以获得认证

开始
广告
© . All rights reserved.