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

 Live Demo

#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

Updated on: 19-Dec-2019

113 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements