在 JavaScript 中檢查醜數


在十進位制數字系統中,醜數是指其唯一的質因數是 2、3 或 5 的正整數。

例如:1 到 10 之間的整數都是醜數,12 也同樣是醜數。

我們的任務是編寫一個 JavaScript 函式,輸入一個數字,並確定它是否為醜數。

我們來寫一寫這個函式的程式碼:

示例

const num = 274;
const isUgly = num => {
   while(num !== 1){
      if(num % 2 === 0){
         num /= 2;
      } else if(num % 3 === 0) {
         num /= 3;
      } else if(num % 5 === 0) {
            num /= 5;
      } else {
         return false;
      };
   };
   return true;
};
console.log(isUgly(num));
console.log(isUgly(60));
console.log(isUgly(140));

輸出

控制檯中的輸出將是:

false
true
false

更新於:31-Aug-2020

914 次瀏覽

開啟你的 事業

完成課程,獲得認證

立即開始
廣告
© . All rights reserved.