Skip to main content
deleted 21 characters in body
Source Link
janos
  • 111.7k
  • 15
  • 152
  • 391

You don't need a loop for this, there is a mathematical solution (= formula) for this:

  • If y - x is divisible by d, then it takes (y - x) / d jumps
  • If y - x is not divisible by d, then it takes (y - x) / d + 1 jumps

In other words:

if ((y - x) % d == 0) {
    return (y - x) / d;
}
return (y - x) / d + 1;

Or the somewhat less readable but more compact:

return (y - x) / d + ((y - x) % d == 0 ? 0 : 1);

You don't need a loop for this, there is a mathematical solution (= formula) for this:

  • If y - x is divisible by d, then it takes (y - x) / d jumps
  • If y - x is not divisible by d, then it takes (y - x) / d + 1 jumps

In other words:

if ((y - x) % d == 0) {
    return (y - x) / d;
}
return (y - x) / d + 1;

Or the somewhat less readable but more compact:

return (y - x) / d + ((y - x) % d == 0 ? 0 : 1);

You don't need a loop for this, there is a mathematical solution:

  • If y - x is divisible by d, then it takes (y - x) / d jumps
  • If y - x is not divisible by d, then it takes (y - x) / d + 1 jumps

In other words:

if ((y - x) % d == 0) {
    return (y - x) / d;
}
return (y - x) / d + 1;

Or the somewhat less readable but more compact:

return (y - x) / d + ((y - x) % d == 0 ? 0 : 1);
Source Link
janos
  • 111.7k
  • 15
  • 152
  • 391

You don't need a loop for this, there is a mathematical solution (= formula) for this:

  • If y - x is divisible by d, then it takes (y - x) / d jumps
  • If y - x is not divisible by d, then it takes (y - x) / d + 1 jumps

In other words:

if ((y - x) % d == 0) {
    return (y - x) / d;
}
return (y - x) / d + 1;

Or the somewhat less readable but more compact:

return (y - x) / d + ((y - x) % d == 0 ? 0 : 1);