Home > Web Front-end > JS Tutorial > Codewars - Beginner Series #um of Numbers

Codewars - Beginner Series #um of Numbers

Patricia Arquette
Release: 2025-01-05 02:25:37
Original
918 people have browsed it

Salutations.

Codewars - Beginner Series #um of Numbers

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:

Codewars - Beginner Series #um of Numbers

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 * rangesum=median∗range

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

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

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

function getSum(a, b)
{
   //Good luck!
}
Copy after login
function getSum(a, b)
{
   let sum = (b ** 2 - a ** 2 + b + a ) / 2 ;
   return sum;
}
Copy after login

We test it and:

Codewars - Beginner Series #um of Numbers

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

getSum(a, b)
Copy after login

(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;
  }
Copy after login

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;
}
Copy after login

Somewhat decent, easy for the reading.

Cya. Drink water ???.

Previous

The above is the detailed content of Codewars - Beginner Series #um of Numbers. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template