The equation to finding the summation of 1 to n is given in the description:
n*(n+1) / 2
Let's assume N is smaller and M is greater. If it is the other way round we can always swap N and M.
If N was 2 and M was 6 and we need to find the summation of 2 to 6, we would find the total summation of 1 to 6 using 6*(6+1)/2 = 21
. And, then we would subtract the summation of N-1 (2-1 = 1
) like so 1*(1+1)/2 = 1
.
The equation of the answer will be (Summation(M) - Summation(N-1)) = 21 - 1 = 20
The critical case for this problem is N can be greater than M :-)
The output of the test case: 6 2 is same as 2 6.