Write a program to check whether a given number is an ugly number.spa
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
.code
Note that 1
is typically treated as an ugly number.blog
ugly number指的是因子最終能分解成2 3 5的數字,1也認爲是特殊的ugly numberit
循環相除,能被2 3 5之一整除的話,繼續循環,知道一個數字不能被2 3 5任何數字整除。此時這個數字不是1的話,則說明這個num不是ugly number,如果1的話則說明是ugly number。class
bool isUgly(int num) { if(num < 1) { return 0; } while(num > 1) { if(num % 2 == 0) { num /= 2; continue; } else if(num % 3 == 0) { num /= 3; continue; } else if(num % 5 == 0) { num /= 5; continue; } return 0; } return 1; }