描述
Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence
1, 2, 3, 4, 5, 6, 8, 9, 10, 12, ...
shows the first 10 ugly numbers. By convention, 1 is included.
Given the integer n,write a program to find and print the n'th ugly number.
輸入
Each line of the input contains a postisive integer n (n <= 1500).Input is terminated by a line with n=0.
輸出
For each line, output the n’th ugly number .:Don’t deal with the line with n=0.
樣例輸入
1
2
9
0
樣例輸出
1
2
10
參考代碼
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.Iterator;
- import java.util.Set;
- import java.util.TreeSet;
- public class Main {
- public static int N = 1601;
- public static Set<Integer> set = new TreeSet<Integer>();
- public static void main(String[] args) throws Exception, IOException{
- init();
- BufferedReader cin = new BufferedReader (new InputStreamReader(System.in));
- while(true){
- int n = Integer.parseInt(cin.readLine());
- if(0 == n)
- break;
- System.out.println(setAt(n));
- }
- }
- private static void init() {
- set.add(1);
- int n = 1;
- int loop = 1;
- while(set.size() < N){
- add2set(n);
- n = setAt(++ loop);
- }
- }
- private static int setAt(int p) {
- int n = 0;
- Iterator<Integer> it = set.iterator();
- int j = 1;
- while(it.hasNext()){
- n = it.next();
- if(j == p)
- return n;
- j ++;
- }
- return n;
- }
- private static void add2set(int n) {
- set.add(n * 2);
- set.add(n * 3);
- set.add(n * 5);
- }
- }