Saturday 28 July 2012

There is an array A[N] 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]. 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]. Solve it without division operator and in O(n).



#include<stdio.h>
void product_digit_exceptIndex(int input[],int output[], int size)
{
    long int i, result;
    result=1;
    for(i=0;i<size;i++)
    {
        output[i]=result;
        result*=input[i];
    }
    result=1;
    for(i=size-1;i>=0;i--)
    {
        output[i]*=result;
        result*=input[i];
    }
}


int main()
{
int input[]={1,2,3,4};
int size = sizeof(input)/sizeof(int);
int output[size];
product_digit_exceptIndex(input,output,size);
int i;
for(i=0;i<size;i++)
{
    printf("%d ",output[i]);
}
return 0;
}

No comments:

Post a Comment