丑数相关的操作
1、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、Write a program to find the n-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
package netease; public class UglyNumber { /** * 判断是会否为丑数 * * @param num * @return */ public static boolean isUgly(int num) { if (num == 0) { return false; } if (num == 1) { return true; } 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 isUgly(num); } /** * 找到第n大的丑数 * * @param n * @return */ public static int nthUglyNumber(int n) { int[] ugly = new int[n]; int index2 = 0; int index3 = 0; int index5 = 0; int factor2 = 2; int factor3 = 3; int factor5 = 5; ugly[0] = 1; for (int i = 1; i < n; i++) { int smallNum = Math.min(Math.min(factor2, factor3), factor5);// 三个数中的最小值 ugly[i] = smallNum; if (factor2 == smallNum) { factor2 = 2 * ugly[++index2];// 分开记录相乘的次数 } if (factor3 == smallNum) { factor3 = 3 * ugly[++index3]; } if (factor5 == smallNum) { factor5 = 5 * ugly[++index5]; } } return ugly[n - 1]; } public static void main(String[] args) { System.out.println(isUgly(0)); System.out.println(nthUglyNumber(10)); } }

浙公网安备 33010602011771号