function fun(start, end) { return (start + end) * (Math.abs(end - start) + 1) / 2 } alert(fun(4, 1)); alert(fun(1, 4)); //1 + 2 + 3 + 4 = 10 alert(fun(5, 2)); alert(fun(2, 5)); //2 + 3 + 4 + 5 = 14