- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures

- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces

# Find N integers with given difference between product and sum in C++

Suppose we have two integers N and D. We have to find a set of N integers, where the difference between their sum and product is the same as D. Suppose the N = 3, and D = 5, then the output will be 1, 2, 8. Here the sum is 1 + 2 + 8 = 11, and product is 1 * 2 * 8 = 16, the difference between 16 and 11 is 5.

We have to solve this problem; we will use one tricky method. Here we will try to find N–2 number of 1s, one 2, and remaining one number N + D. So the sum, product and difference will be −

- Sum = (N – 2)*1 + 2 + (N + D) = 2*N + D
- Product = (N – 2)*1 * 2 * (N + D) = 2*N + 2*D
- Difference = (2*N + 2*D) – (2*N + D) = D

## Example

#include<iostream> using namespace std; void getNNumbers(int n, int d) { for (int i = 0; i < n - 2; i++) cout << 1 << " "; cout << 2 << " "; cout << n + d << endl; } int main() { int N = 5, D = 8; getNNumbers(N, D); }

## Output

1 1 1 2 13

- Related Articles
- Maximum GCD of N integers with given product in C++
- Find four factors of N with maximum product and sum equal to N in C++
- C++ find four factors of N with maximum product and sum equal to N .
- Find two numbers with sum and product both same as N in C++
- Difference between sum and product of an array in JavaScript
- Find two numbers with sum and product both same as N in C++ Program
- Find four factors of N with maximum product and sum equal to N - Set-2 in Python
- Find four factors of N with maximum product and sum equal to N - Set-2 in C++
- Find four factors of N with maximum product and sum equal to N - Set-2 in Python Program
- C++ program to find two numbers with sum and product both same as N
- Difference between product and sum of digits of a number in JavaScript
- Find N Unique Integers Sum up to Zero in C++
- Find the sum of all even integers between 101 and 999.
- Absolute difference between sum and product of roots of a quartic equation?
- Difference Between Product and Process

Advertisements