# Ugly Number I and II

/*
* 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.
*/
public boolean nthSuperUglyNumber1(int num) {
/*if(num!=1){
while(num%2==0)
num=num/2;
if(num == 1)return true;
else{
while(num%3==0)
num=num/3;
if(num == 1)return true;
else{
while(num%5==0)
num=num/5;
if(num == 1)return true;
else return false;
}
}
}
return false;*/

if(num<=0) return false;
if(num==1) return true;

while(num>=2 && num%2==0) num/=2;
while(num>=3 && num%3==0) num/=3;
while(num>=5 && num%5==0) num/=5;

return num==1;

}
/*
* Write a program to find the nth super ugly number.

Super ugly numbers are positive numbers whose all prime factors are in the given prime list primes of size k.
For example, [1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32] is the sequence of the first 12
super ugly numbers given primes = [2, 7, 13, 19] of size 4.

Note:
(1) 1 is a super ugly number for any given primes.
(2) The given numbers in primes are in ascending order.
(3) 0 < k ≤ 100, 0 < n ≤ 106, 0 < primes[i] < 1000.
*/
/*
* 超级丑数。跟丑数II很类似，只不过这次primes从2, 3, 5变成了一个size k的list。方法应该有几种，一种是维护一个size K的
* min-oriented heap，heap里是k个queue，和Ugly Number II的方法一样，取最小的那一个，然后更新其他Queue里的元素，
* n--，最后n = 1时循环结束。  另外一种是类似dynamic programming的方法，主要参考了larrywant2014大神的代码。
* 维护一个index数组，维护一个dp数组。每次遍历更新的转移方程非常巧妙，min = dp[[index[j]]] * primes[j]。
* 之后再便利一次primes来update每个数在index[]中的使用次数。
*/
public int nthSuperUglyNumber(int n, int[] primes) {
int len=primes.length;
int[] res= new int[n+1];//村结果
int[] index=new int[len];//存因子
res[0]=1;
if(n<=1)return res[0];
for(int i=1;i<n;i++){
int num=Integer.MAX_VALUE;
for(int j=0;j<len;j++)
num=Math.min(num, primes[j]*res[index[j]]);
res[i]=num;
for(int j=0;j<len;j++)
if(res[i]%primes[j]==0)index[j]++;
}
return res[n-1];
}

/*
* 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.

Note that 1 is typically treated as an ugly number.

*/

public int nthUglyNumber(int n) {
if(n<0)return 0;
int[] nums=new int[n+1];
int index2,index3,index5;
index2=1;
index3=1;
index5=1;
nums[0]=0;
nums[1]=1;
for(int i=2;i<=n;i++){
int min=minOfRange(nums[index2],nums[index3],nums[index5]);

if(min==nums[index2]*2){

index2++;
}
if(min==nums[index3]*3){
index3++;
}if(min==nums[index5]*5){
index5++;
}
nums[i]=min;
System.out.println(nums[i]);
System.out.println("index2:"+index2+"\t"+"index3:"+index3+"\t"+"index5:"+index5+"\t");
}
return nums[n];

}
private int minOfRange(int index2, int index3, int index5) {
// TODO Auto-generated method stub
int min=index2*2<index3*3?index2*2:index3*3;

return min<index5*5?min:index5*5;
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：Ugly Number I and II 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)