bigpotato

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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:

  1. 1 is typically treated as an ugly number.
  2. Input is within the 32-bit signed integer range.

 

检测一个数是否是ugly number。

ugly number 满足以下条件:

  1. 正整数;
  2. 质因数仅含2、3、5;
  3. 特别地,1是ugly number。

由2可知,如果一个数是ugly number,除去这个数所有2、3、5的因数,结果为1。

代码如下:

bool 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;
}

  

posted on 2018-03-18 17:37  bigpotato  阅读(123)  评论(0)    收藏  举报