Given two integers, which can be positive and negative, find the sum of all the numbers between including them too and return it. If both numbers are equal return a or b.

Note! a and b are not ordered!

Expected output is as follows:

1 2 3 4 5 6 7 |
Example: 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 |

#### Sum of all the numbers solution – the beginner’s way

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
function GetSum( a,b ){ let lower,higher; let result=0; //return either of it if they are equal if(a == b){ return a; }else{ if(a > b){ higher = a; lower = b }else{ higher = b; lower = a; } for(i=lower;i<=higher;i++){ result += i; } } return result; } console.log(GetSum( 3,9 )) |

You can play around with the code in JSFiddle

#### Sum of all the numbers solution – the clever way using javascript recursion

1 2 3 4 5 6 7 8 9 10 11 |
function GetSum( a,b ){ if (a == b) { return a } else if (a < b) { return a + GetSum(a+1, b) }else { return a + GetSum(a-1,b) }; } console.log(GetSum(-1,2)); |

You can play around with the code on JSfiddle