本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/49431329
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; } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-12-04 17:09:53