Codewars - Beginner Series #3 Sum of Numbers
Nicolás Bost

Nicolás Bost @dantedinopegassi

About: Yo tratando de usar un 𝒷𝓁ℴ𝑔 para jugar menos jueguitos

Joined:
Dec 30, 2024

Codewars - Beginner Series #3 Sum of Numbers

Publish Date: Jan 3
0 0

Salutations.

asdf turtle

I'm posting Codewars challenges and my thought process in this series. I'm using JS and Node 18 whenever possible. Just for the sake of clarity, I'm making fair use of them.

So, next in this series is Sum of Numbers. In this specific problem, it's more math than coding. See, you need to calculate an area. In this graph, for example, we show all values between -5 and 4:

Desmos graph

You can use integration if you so desired, but there's a simpler route. Since we're dealing with linear functions, we can search for the median and multiply for the range:

sum=medianrangesum = median * range

sum=bba2(ba+1)sum = b - \frac{b-a}{2} * (b - a + 1)

sum=b2a2+b+a2sum = \frac{b^2 - a^2 + b + a}{2}

So we just need to insert that equation in the code. It starts like this:

function getSum(a, b)
{
   //Good luck!
}
Enter fullscreen mode Exit fullscreen mode
function getSum(a, b)
{
   let sum = (b ** 2 - a ** 2 + b + a ) / 2 ;
   return sum;
}
Enter fullscreen mode Exit fullscreen mode

We test it and:

Poh frustration

But why? I know the equation is correctly simplified, so... Oh. This is the problem:

getSum(a, b)
Enter fullscreen mode Exit fullscreen mode

(a,b) in exactly that order. It works if the input is (-5,4), but not if it's (4,-5). Fix? You could code an "if" statement for both situations. I won't do it like that though. I'll do this:

if (a > b){
    let c = a;
    a = b;
    b = c;
  }
Enter fullscreen mode Exit fullscreen mode

And so, we put together everything:

function getSum(a, b)
{
  if (a > b){
    let c = a;
    a = b;
    b = c;
  }
  let sum = (b ** 2 - a ** 2 + b + a ) / 2 ;
  return sum;
}
Enter fullscreen mode Exit fullscreen mode

Somewhat decent, easy for the reading.

Cya. Drink water 💧💧💧.

Previous

Comments 0 total

    Add comment