Here is a question from previous HackerEarth Challenge -
Roy has a matrix of size NxN. Rows and Columns are numbered from 0 to N-1. jth column of ith row contains absolute difference between i and j. In other words, Matrix[i][j] = abs(i-j) where 0 ≤ i, j < N. Your task is to find sum of this matrix i.e.
sum = 0
for i=0 to N-1
for j=0 to N-1
sum += Matrix[i][j]
and here is my solution to this problem -
public static long getSum(int num, long acc) {
if (num == 1)
return acc;
long sum = 0;
for (int i = 0; i < num; i++) {
sum += i;
}
sum = sum * 2;
return getSum(num - 1, acc + sum);
}
But this function fails for large number like say anything greater than 4500. I get Stack Over Flow Error. Here I have tried two things basically to keep the code optimized -
- use tail recursion, and
- keep running time of this function of order 'n'
So please tell me if I have achieved the two things here correctly. If yes what else can I do to optimize this code. Thanks for your help.