歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

Java程序練習-Ugly Numbers

描述
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
參考代碼

  1. import java.io.BufferedReader;  
  2. import java.io.IOException;  
  3. import java.io.InputStreamReader;  
  4. import java.util.Iterator;  
  5. import java.util.Set;  
  6. import java.util.TreeSet;  
  7. public class Main {  
  8.     public static int N = 1601;  
  9.     public static Set<Integer> set = new TreeSet<Integer>();  
  10.     public static void main(String[] args) throws Exception, IOException{  
  11.         init();  
  12.         BufferedReader  cin = new BufferedReader (new InputStreamReader(System.in));  
  13.         while(true){  
  14.             int n = Integer.parseInt(cin.readLine());  
  15.             if(0 == n)  
  16.                 break;  
  17.             System.out.println(setAt(n));  
  18.         }  
  19.     }  
  20.     private static void init() {  
  21.         set.add(1);  
  22.         int n = 1;  
  23.         int loop = 1;  
  24.         while(set.size() < N){  
  25.             add2set(n);  
  26.             n = setAt(++ loop);  
  27.         }  
  28.     }  
  29.     private static int setAt(int p) {  
  30.         int n = 0;  
  31.         Iterator<Integer> it = set.iterator();  
  32.         int j = 1;  
  33.         while(it.hasNext()){  
  34.             n = it.next();  
  35.             if(j == p)  
  36.                 return n;  
  37.             j ++;  
  38.         }  
  39.         return n;  
  40.     }  
  41.     private static void add2set(int n) {  
  42.         set.add(n * 2);  
  43.         set.add(n * 3);  
  44.         set.add(n * 5);  
  45.     }  
  46. }  
Copyright © Linux教程網 All Rights Reserved