问题描述

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,特别的,1算作丑数。

问题分析

素数因子只有2,3,5,也就是说这个数N只能被这3个素数整除,不断的执行N/2,直到N%2!=0,则可以排去掉素数因子2,3、5同理。去掉这三个素数因子后,如果N!=1,则说明还有其它的素数因子,N不为丑数。

代码

Java代码:

public class Solution {
	    public boolean isUgly(int num) {
	    	if(num<=0) return false;
	    	if(num==1) return true;
	    	while(num%2==0) {
	        	num/=2;
	        }
	        while(num%3==0) {
	        	num/=3;
	        }
	        while(num%5==0) {
	        	num/=5;
	        }
	    	return num==1;
	    }
	}