Processing math: 100%

在 C++ 中查找满足给定方程的 n 个正整数


在这个问题中,我们给定三个值 A、B 和 N。我们的任务是找到满足给定方程的 n 个正整数。

问题描述 − 我们需要找到满足这两个方程的 N 个正值,

x12 + x22 + … xn2 ≥ A
x1 + x2 + … xn ≤ B

如果存在 n 个值,则打印 n 个值,否则打印 -1。

让我们举个例子来理解这个问题,

输入

N = 4, A = 65, B = 16

输出

1 1 1 8

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

解释

方程为 −

12 + 12 + 12 + 82 = 1 + 1 + 1 + 64 = 67 ≥ 65
1 + 1 + 1 + 8 = 11 < 16

解决方案

解决此问题的一个简单方法是最大化平方和。这个想法是使用一个数字作为主要数字来最大化平方和,并使用另一个数字作为 1。因此,使用此方法,我们可以最大化平方和并满足求和条件。

程序说明我们解决方案的工作原理,

示例

 在线演示

#include <bits/stdc++.h>
using namespace std;
void findNintegers(int N, int A, int B) {
   vector<int> numbers;
   for (int i = 0; i < N - 1; i++)
      numbers.push_back(1);
   if (B - (N - 1) <= 0) {
      cout << "-1";
      return;
   }
   numbers.push_back(B - (N - 1));
   int vals = 0;
   for (int i = 0; i < N; i++)
      vals += numbers[i] * numbers[i];
   if (vals < A) {
      cout << "-1";
      return;
   }
   for (int i = 0; i < N; i++)
      cout << numbers[i] << " ";
}
int main(){
   int N = 4, A = 65, B = 17;
   cout<<N<<" positive integers that satisfy the given equations are ";
   findNintegers(N, A, B);
   return 0;
}

输出

4 positive integers that satisfy the given equations are 1 1 1 14

更新于: 2021年3月12日

227 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告