Tuesday, May 3, 2011

Pubmatic Question: Average of the elements of an array

Only Problem in this question is to tackle integer overflow. Instead of doing
(a[0] + a[1] + ....a [n-1])  /  n
do as following --
a[0]  / n + a[1]  /  n + ..... a[n-1]  /  n 


3 comments:

  1. sir I think maintaining reminder and questiont will be more accurate.

    Your solution can leads to problems for example on 8 bit machine array of 2^8 with every element as 1 might give wrong result

    Thanks
    Paras Malik

    ReplyDelete
  2. speed will be directly proportional to the number of division operations. In my case number of divisions will be <=n and your case it is =n.

    Thanks
    Paras Malik

    ReplyDelete
  3. Agree.. It is just a way to achieve it. Can always find better solution.

    ReplyDelete