Find n-variables from n sum equations with one missing in C++


In this problem, we are given an array sum[] consisting of a sum of (n-1) variables given as,

Sum[1] = x2 + x3 + x4 + … xn
Sum[2] = x1 + x3 + x4 + … xn
.
.
Sum[i] = x2 + x3 + x4 + … x(i-1) + x(i+1) + … + xn
.
.
Sum[n] = x1 + x2 + x3 + … x(n-1)
Our task is to find the value of x1, x2,... xn.

Let’s take an example to understand the problem,

Input

sum[] = {6, 6, 6, 6, 6, 6, 6}

Output

x1 = 1, x2 = 1, x3 = 1, x4 = 1, x5 = 1, x6 = 1, x7 = 1

Explanation

arr[1] = 1 + 1 + 1 + 1 + 1 + 1 = 6

Solution Approach

Let the sum of all variables be sumX,

sumX = x1 + x2 + x3 + … + xn

So, the values of sum array are −

sum[1] = x2 + x3 + x4 + … xn
= -x1 + x1 + x2 + x3 + x4 + … xn
= sumX - x1

Similarly,

sum[2] = sumX - x2
sum[3] = sumX - x3
.
sum[i] = sumX - xi
.
sum[n] = sumX - xn

Adding all the sum arrays we get,

Sum[1] + sum[2] + … sum[n] = sumX - x1 + sumX - x2 + … + sumX - xn
arrSum = n*sumX - (x1 + x2 + x3 … xn)
arrSum = n*SumX - (x1 + x2 + x3 … xn)
arrSum = sumX*(n-1)
sumX = arrSum/ (n-1)

Using this value of sumX, we can find the values of x1, x2…

So,

x1 = sumX - sum[1]
x2 = sumX - sum[2]
..
xi = sumX - sum[i]
..
xn = sumX - sum[n]

Program to illustrate the working of our solution,

Example

 Live Demo

#include <iostream>
using namespace std;
void calcSumVariables(int sum[], int n) {
   float SUMX = 0;
   for (int i = 0; i < n; i++) {
      SUMX += sum[i];
   }
   SUMX /= (n - 1);
   for (int i = 0; i < n; i++)
      cout<<"\nx"<<(i + 1)<<" = "<<(SUMX - sum[i]);
}
int main(){
   int sum[] = {3, 8, 6, 7, 4, 5, 9 };
   int N = sizeof(sum) / sizeof(sum[0]);
   cout<<"The value of variables that form the sum are ";
   calcSumVariables(sum, N);
   return 0;
}

Output

The value of variables that form the sum are

x1 = 4
x2 = -1
x3 = 1
x4 = 0
x5 = 3
x6 = 2
x7 = -2

Updated on: 13-Mar-2021

39 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements