丑数
如果一个数的素因子只包含2,3,5或7,那么我们把这种数叫做丑数。序列1,2,3,4,5,6,7,8,9,10,12,14,15,16,18,20,21,24,25,27.. 求出第n个位置的丑数
package day1205_丑数;
/*如果一个数的素因子只包含2,3,5或7,
* 那么我们把这种数叫做丑数。
* 序列1,2,3,4,5,6,7,8,9,10,12,14,15,
* 16,18,20,21,24,25,27..
* 求出第n个位置的丑数*/
import java.util.LinkedList;
import java.util.Scanner;
public class Test1 {
public static void main(String[] args) {
System.out.println("求第几个丑数");
int n = new Scanner(System.in).nextInt();
long r = f(n);
System.out.println(r);
long s = s(n);
System.out.println(s);
}
//方法1
private static long s(int n) {
if (n == 1) {
return 1;
}
int count = 1;
for (int i = 2; ; i++) {
long t = i;
while(t%2==0) t/=2;
while(t%3==0) t/=3;
while(t%5==0) t/=5;
if (t == 1) {
count++;
if (count == n) {
return i;
}
}
}
}
/* 2
*
* -----------*2
* 3
* -----------*3
* 5
* -----------*5
* 1 .取最小值
*
* 2 .乘2,3,5放入三个集合
* r = 2 3 4 5 6 8...
* */
//方法2
private static long f(int n) {
if (n==1) {
return 1;
}
LinkedList<Long> list2 = new LinkedList<>();
LinkedList<Long> list3 = new LinkedList<>();
LinkedList<Long> list5 = new LinkedList<>();
list2.add(2L);
list3.add(3L);
list5.add(5L);
//保存每一次取出的丑数
long r = 0;
//从第2个,求到第n个
for (int i =2; i <=n; i++) {
long a = list2.getFirst();
long b = list3.getFirst();
long c = list5.getFirst();
r = a<b?(a<c?a:c):(b<c?b:c);//三目求三个数最小值
//r = Math.min(a, Math.min(b, c));
if(r == a) list2.removeFirst();
if(r == b) list3.removeFirst();
if(r == c) list5.removeFirst();
list2.add(r*2);
list3.add(r*3);
list5.add(r*5);
}
return r;
}
}