Finding number of diagonals in a matrix There is a square matrix of size $N*N$. The matrix contains $M$ numbers of $0's$ which needs to be fit in $first$ $2k+1$ ($k < N$) diagonals (the main diagonal and $k$ diagonals immediately above and $k$ below the main diagonal). 
Suppose I have $M=5$, so I have to fit them in $3 (k=1)$diagonals, since the $3$ diagonals together contain $7$ spots and there are only five $0's$ available. So here $k=1$.
If $M=3$ then the value of $K$ would be $0$ as all the $0's$ would fit the main diagonal itself.
How do I calculate for any general square matrix the value of $k$ given value of $M,N$ ? 
 A: Given $N$, the number of spots in the first $2k + 1$ diagonals - as your question seems to ask - can be derived as follows.
You notice that for $k=0$, you get exactly $N$. For every $k>0$, you get a number greater than the number of spots you had in the $k-1$-th iteration. Or, you can suppose you're getting the sum of every integer from 1 to $N$, then subtracting the sum of all integers from 1 to $N-(k+1)$; then you double this amount and subtract $N$ again.
If you think about your matrix and rotate it mentally by 45°, you'll notice it looks like two triangles joined by the bottom. The sum of all the spots in a triangle-like number structure like this is exactly equal to the sum of all integers from 1 to the number of spots in the base of the triangle. You can easily check that. All I'm doing is: get the sum of all the spots in the triangle that makes up half of the matrix, then subtract the spots of a smaller triangle - so that all that is left are the main diagonal and $k$ more diagonals; double that number and since we're left with the correct amount of non-main-diagonal spots and twice the spots of the main diagonal, we subtract it.
$$ S_{pots} = 2(\frac{N(N+1)}{2} - \frac{(N-(k+1))(N-(k+1)+1)}{2}) - N$$
And you can work out a simplified equation by yourself.
Now that you've got an answer that depends on $k$, given an M you just choose a $k$ so that:
$$M \le S_{pots}$$
And you're done.
