题目

Write a program to check whether a given number is an ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.

Note that 1 is typically treated as an ugly number.

大致意思

判断一个数字是否为ugly数字。要是它只能被2、3、5这三个数字除尽的话,他就是。比如 6 = 2 * 3, 8 = 2 * 2 * 2。所以6和8是。但是14 = 2 * 7,所以14不是

解决方案

  • 我们可以挨个进行2 3 5进行除,判断最后是否为1

源代码

var isUgly = function(num) {
  if (num === 0) return false
  var n
  while (num !== 1) {
    n = num / 5
    if (Math.floor(n) === n) {
      num = n
      continue
    }

    n = num / 3
    if (Math.floor(n) === n) {
      num = n
      continue
    }

    n = num / 2
    if (Math.floor(n) === n) {
      num = n
      continue
    }

    return false
  }

  return true
};