Arrays of numbers
We have two arrays of numbers (say a and b).
One is filled (say a) and the other (b) is empty. Now we have to fill the empty array (b) in such a way that number on any position is multiplication of all numbers except the number on same position in the other array.
arrayB[0]=arrayA[1]*arrayA[2]*arrayA[3]*arrayA[4].......*arrayA[arrayA.length-1]
arrayB[1]=arrayA[0]*arrayA[2]*arrayA[3]*arrayA[4].......*arrayA[arrayA.length-1]
arrayB[2]=arrayA[0]*arrayA[1]*arrayA[3]*arrayA[4].......*arrayA[arrayA.length-1]
...............
arrayB[arrayA.length-1]=arrayA[0]*arrayA[1]*arrayA[2]*arrayA[3].....*arrayA[arrayA.length-2]
Give best method to do this.
One way is to find total multiplication of all numbers in arrayA and then find the number for arrayB by dividing the total amount by number on same position is arrayA.
i.e.
totalAmount=1;
for(int i=0; i<arrayA.length; i++)
{
totalAmount=totalAmount*arrayA[i];
}
for(int i=0; i<arrayA.length; i++)
{
arrayB[i]=totalAmount/arrayA[i];
}
Other way of doing so, is the following:
int totalBefore=1;
int totalAfter=1;
for(int i=0; i< arrayA.length; i++)
{
arrayB[i]=1;
}
for(int i=1;i< arrayA.length; i++)
{
totalBefore = totalBefore * arrayA[i-1];
arrayB[i] *= totalBefore;
}
for(int i=arrayA.length-2;i >= 0;i--)
{
totalAfter = totalAfter * arrayA[i+1];
arrayB[i] *= totalAfter;
}
For more such articles, Visit: http://www.pankajbatra.com
No comments:
Post a Comment