Problem7

简介:

1.package com.shui.mu.yao.io.algorithm;  
2.  
3.import java.util.ArrayList;  
4.import java.util.Arrays;  
5.import java.util.List;  
6.  
7./** 
8. *  
9. * @author shuimuqinghua77 @date 2011-11-3上午10:56:33 
10. *  
11. */  
12./** 
13. * By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see 
14. * that the 6th prime is 13. What is the 10 001st prime number? 
15. */  
16.public class Problem7 {  
17.    private static List<Long> seed = new ArrayList<Long>();  
18.    private static long count=7;  
19.    static {  
20.        seed.add(2l);  
21.        seed.add(3l);  
22.        seed.add(5l);  
23.  
24.    }  
25.  
26.    public static long findPrime(int index) throws Exception {  
27.        while (seed.size()<index) {  
28.            if(count==Long.MAX_VALUE)  
29.            {  
30.                throw new Exception("超过long类型最大值");  
31.            }  
32.            int flag=0;  
33.            for(long l:seed){  
34.                if(count%l==0)  
35.                {  
36.                    flag=1;  
37.                    break;  
38.                }  
39.                  
40.            }  
41.            if(flag==0)  
42.            seed.add(count);  
43.            count++;  
44.        }  
45.        return seed.get(index-1);  
46.    }  
47.    public static void main(String[] args) throws Exception {  
48.        long result=findPrime(10001);  
49.        System.out.println(result);  
50.        System.out.println(Arrays.toString(seed.toArray()));  
51.    }  
52.}  

相关文章
|
7月前
|
数据挖掘
|
Go C++
P1001 A+B Problem
P1001 A+B Problem
118 0
|
算法框架/工具
|
存储 索引
|
数据库管理