# Find n positive integers that satisfy the given equations in C++

C++Server Side ProgrammingProgramming

In this problem, we are given three values A, B and N. Our task is to Find n positive integers that satisfy the given equations.

Problem Description − We need to find the N positive values that satisfy both the equations,

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

Print n values if present, otherwise print -1.

Let’s take an example to understand the problem,

## Input

N = 4, A = 65, B = 16

## Output

1 1 1 8

## Explanation

The equations are −

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

## Solution Approach

A simple solution to the problem is by maximising the square sum. The idea is to use one number as the primary number to maximise the square sum and using another as 1. Thus using this we can maximise the square sum and satisfy the sum condition.

Program to illustrate the working of our solution,

## Example

Live Demo

#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;
}

## Output

4 positive integers that satisfy the given equations are 1 1 1 14
Published on 12-Mar-2021 08:23:26