在 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
解釋
方程為 −
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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP