https://www.codewars.com/kata/beginner-series-number-3-sum-of-numbers/train/java
Instructions
Given two integers a and b, which can be positive or negative, find the sum of all the numbers between including them too and return it. If the two numbers are equal return a or b.
Note: a and b are not ordered!
Examples
GetSum(1, 0) == 1 // 1 + 0 = 1
GetSum(1, 2) == 3 // 1 + 2 = 3
GetSum(0, 1) == 1 // 0 + 1 = 1
GetSum(1, 1) == 1 // 1 Since both are same
GetSum(-1, 0) == -1 // -1 + 0 = -1
GetSum(-1, 2) == 2 // -1 + 0 + 1 + 2 = 2
Solution
public class Sum
{
public int GetSum(int smallnum, int bignum)
{
int sum = 0;
if(bignum<smallnum) { return GetSum(bignum, smallnum); }
else{
// s = n/2(a+l)
// s : sum
// a : firstnum
// l : lastnum
// n : (l-a+1)
sum = ((bignum-smallnum+1)*(smallnum+bignum)/2);
return sum;
}
}
}