Files
30-seconds-of-code/snippets_archive/howManyTimes.md
Angelos Chalaris 0425ebefe7 Archive, multitagging, cleanup
Cleaned up the current snippets for consistency and minor problems, added multiple tags to most of them, archived a few.
2018-01-05 16:33:54 +02:00

809 B

howManyTimes

Returns the number of times num can be divided by divisor (integer or fractional) without getting a fractional answer. Works for both negative and positive integers.

If divisor is -1 or 1 return Infinity. If divisor is -0 or 0 return 0. Otherwise, keep dividing num with divisor and incrementing i, while the result is an integer. Return the number of times the loop was executed, i.

const howManyTimes = (num, divisor) => {
  if (divisor === 1 || divisor === -1) return Infinity;
  if (divisor === 0) return 0;
  let i = 0;
  while (Number.isInteger(num / divisor)) {
    i++;
    num = num / divisor;
  }
  return i;
};
howManyTimes(100, 2); // 2
howManyTimes(100, 2.5); // 2
howManyTimes(100, 0); // 0
howManyTimes(100, -1); // Infinity