丑数就是只包含质因数 2, 3, 5 的正整数。
1.判断丑数
2.找到第n个丑数
(代码很容易看懂)
public class UglyNum {
public static void main(String[] args){
UglyNum a = new UglyNum();
Scanner scanner = new Scanner(System.in);
int n;
while (true){
n = scanner.nextInt();
System.out.print(a.isUgly(n));
System.out.print(a.find_n_UglyNum(n));
}
}
public boolean isUgly(int num) {
if(num==0)
return false;
while (num%2==0){
num = num/2;
}
while (num%3==0){
num = num/3;
}
while (num%5==0){
num = num/5;
}
if(num==1)
return true;
return false;
}
/*
*丑数由2*a+3*b+5*c组成
*/
public int find_n_UglyNum(int n){
//第一个丑数是1
int a=0;
int b=0;
int c = 0;
int[] arr = new int[n];
arr[0] = 1;
for(int i = 1;i<n;i++){
//依次找到第i个丑数
int temp = Math.min( Math.min(2*arr[a],3*arr[b]),5*arr[c]);
if(temp==2*arr[a]){
a++;
}
if(temp==3*arr[b]){
b++;
}
if(temp==5*arr[c]) {
c++;
}
arr[i] = temp;
}
return arr[n-1];
}
}