var N = 9; var count = 0; for (var i = 1; i <= Math.min(4, N); ++i) { count += Math.min(N - i, 9) - Math.max(N - i - 9, 0) + 1; } alert(count);