Saturday, January 30, 2016

Array of numbers multiplication

Array of numbers multiplication


Problem:
There is an array A[] of n numbers. You have to compose an array Output[n] such that Output[i] will be equal to multiplication of all the elements of A[n] except A[i]. Solve it without division operator and in O(n).
For example Output[0] will be multiplication of A[1] to A[n-1] and Output[1] will be multiplication of A[0] and from A[2] to A[n-1].
Example:
A: {4, 3, 2, 1, 2}
Output: {12, 16, 24, 48, 24}
Solution:
1
2
3
4
5
6
7
8
9
10
11
12
void Multiplication(int A[], int Output[], int n) {
  int left = 1;
  int right = 1;
  for (int i = 0; i < n; i++)
      Output[i] = 1;
  for (int i = 0; i < n; i++) {
    Output[i] *= left;
    Output[n - 1 - i] *= right;
    left *= A[i];
    right *= A[n - 1 - i];
  }
}

No comments:

Post a Comment