first I tried using a matrix, exceeds time limit,then use pure math approach.... this problem is not difficult, but have to be really careful when coding....