Problem7

本文介绍了一个Java程序,该程序通过一种简单的方法来找出第10001个质数。程序使用了一个种子列表来保存已知的质数,并逐步测试每个可能的质数候选者,直到找到所需的第10001个质数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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.}  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值