[题目]
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.
[题目解析] 题意要求给定一个数,判断是否为丑数。先来看丑数的定义:质因子只包含2、3或者5的正整数为丑数,即当一个数如14含有另外的质因子7的时候,则不是丑数。根据定义,可以对给定的整数进行2、3或者5因子不断拆解,直到结束,如果不含有别的质因子,则为丑数。
public boolean isUgly(int num) { if(num <= 0) return false; if(num == 1) return true; while(num > 1){ if(num%2 == 0) num = num/2; else if(num%3 == 0) num = num/3; else if(num%5 == 0) num = num/5; else return false; } return true; }