How to know how many numbers there are from x to y?

Asked

Viewed 523 times

-4

For example from 0 to 60. Obviously I know how many numbers there are, but what I know is how to make my algorithm figure that out mathematically.

  • 3

    numero maior - numero menor = total de numeros entre eles

  • Make a for totaling/counting the iterations. In positive numbers it is very evident that the last is total number but in negative numbers ... for example how many numbers you have of -3 until 0?

  • 3

    @rray I find a very tie Overkill to the problem.

  • 3

    Hello David. You can clarify the question and include an example where you cannot write code to solve, and also the programming language you use.

  • Overkill is an American thrash metal band formed in 1980 in New Jersey and in Renam’s commentary which means?

  • 1

    @Leocaracciolo too much work/effort for little result in other words the cost is too high. Then you run out of coffee and give that kind of suggestion haha xD ... Epic fail...

  • 1

    @rray in qq right case of a simple mathematical operation is a lot of work/effort

  • @Leocaracciolo yes, if you want to take the doubt can make a measurement.

  • @rray is not the case, the customer is rich and willing to pay qq price since he had in his hands something very cheap and fundamental. In fact the question does not speak of performance.

Show 4 more comments

1 answer

7

function quantosNumerosExistem(x, y) {
    return Math.abs(y - x) + 1;
}

document.write(
    " De 3 até 10: " + quantosNumerosExistem(3, 10) + "<br>" +
    " De 0 até 60: " + quantosNumerosExistem(0, 60) + "<br>" +
    " De -2 até 2: " + quantosNumerosExistem(-2, 2) + "<br>" +
    " De 0 até 0: " + quantosNumerosExistem(0, 0) + "<br>" +
    " De 0 até 1: " + quantosNumerosExistem(0, 1) + "<br>" +
    " De -10 até -8: " + quantosNumerosExistem(-10, -8)
);
   

  • 1

    Boot in Math.abs before x and y in case of x = -90; y = -12; otherwise will go wrong, Math.abs(x)

  • 1

    @Guilhermelautert Feito.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.