
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find n positive integers that satisfy the given equations in C++
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
#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
- Related Questions & Answers
- Count all possible N digit numbers that satisfy the given condition in C++
- Find numbers a and b that satisfy the given condition in C++
- Find the largest interval that contains exactly one of the given N integers In C++
- Count subsets that satisfy the given condition in C++
- Find n-variables from n sum equations with one missing in C++
- Find N integers with given difference between product and sum in C++
- Find the Number of Sextuplets that Satisfy an Equation using C++
- C++ program to find out the number of pairs in an array that satisfy a given condition
- Program to find number of subsequences that satisfy the given sum condition using Python
- Find x, y, z that satisfy 2/n = 1/x + 1/y + 1/z in C++
- Write a program in C++ to find the missing positive number in a given array of unsorted integers
- Maximum GCD of N integers with given product in C++
- Ways to write N as sum of two or more positive integers in C++
- Find smallest number n such that n XOR n+1 equals to given k in C++
- Find a range that covers all the elements of given N ranges in C++
Advertisements