:: [intv] a={2, 3, 4, 5}, find c, s.t. c[0] = 3*4*5, c[1] = 2*4*5 w/o div. ::
HOME


[Date Prev][Date Next][Date Index]

[intv] a={2, 3, 4, 5}, find c, s.t. c[0] = 3*4*5, c[1] = 2*4*5 w/o div.


Below is the solution.

//Problem: Given an array of integers. say a = {2, 4, 3, 5, 6};
//Find an array c, such that c[0] = 4*3*5*6, c[1] = 2*3*5*6 and so on.
//Note that you cannot use division and it should be in O(n).
//Save as: main.cpp and compile as: g++ -o main main.cpp

#include <iostream>
using namespace std;

int *setMulArray (int *, int);

int main(){
  int a[6] = {2, 4, 3, 5, 6, 3};
  int *c;

  c = setMulArray(a, 6);
  for (int i = 0; i < 6; i++){
    cout << a[i] << "  " << c[i] << endl;
  }
}

int *setMulArray (int *a, int aSize){
  int *c;
  c = (int *) malloc(sizeof(int)*aSize);
  if (c == NULL) {cout << "ERROR" << endl;}

  int allleft = 1;
  for (int i = 0; i < aSize; i++){
    c[i] = allleft;
    allleft *= a[i];
  }

  int allright = 1;
  for (int i = (aSize-1); i >= 0; i--){
    c[i] *= allright;
    allright *= a[i];
  }

  return c;
}


Comments and corrections are appreciated and can be sent to papers@mia.ece.uic.edu. Click here for ©opyright information.