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.
思路:
(1)該題題意為給定一個數,判斷該數是否為“丑數”。
(2)這道題很基礎。丑數是因子只含有2、3、5的數。所以只需對這三個數循環取余判斷即可。這裡不再累贅。
(3)詳情見下方代碼。希望本文對你有所幫助。
public class Ugly_Number {
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
System.err.println(i + == + isUgly(i));
}
}
// 2 3 5
public static boolean isUgly(int num) {
if (num == 1)
return true;
while (num >= 2 && num % 2 == 0) {
num = num / 2;
}
while (num >= 3 && num % 3 == 0) {
num = num / 3;
}
while (num >= 5 && num % 5 == 0) {
num = num / 5;
}
return num == 1 ? true : false;
}
}