Skip to content

Commit

Permalink
day 153
Browse files Browse the repository at this point in the history
  • Loading branch information
jwardoin committed Aug 25, 2022
1 parent 235286a commit a427269
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions sumOfNumbers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// Given two integers a and b, which can be positive or negative, find the sum of all the integers between and including them and return it. If the two numbers are equal return a or b.

// Note: a and b are not ordered!

// Examples (a, b) --> output (explanation)
// (1, 0) --> 1 (1 + 0 = 1)
// (1, 2) --> 3 (1 + 2 = 3)
// (0, 1) --> 1 (0 + 1 = 1)
// (1, 1) --> 1 (1 since both are same)
// (-1, 0) --> -1 (-1 + 0 = -1)
// (-1, 2) --> 2 (-1 + 0 + 1 + 2 = 2)

// my original solution

function getSum(a, b) {
let sum = 0;
for (let i = Math.min(a, b); i <= Math.max(a, b); i++) {
sum += i;
}
return sum;
}

// what I learned from others' solutions

function GetSum(a, b) {
return ((Math.abs(a - b) + 1) * (a + b)) / 2; // formula for return sequential integers
}

0 comments on commit a427269

Please sign in to comment.