手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

Java程序练习-Ugly Numbers

[日期:2011-10-03] 来源:Linux社区  作者:binfeihan [字体:大 中 小]
描述
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. }  
linux
相关资讯       Java 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款