By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
译文:
观察第一组质数可知,第6位质数为13,那么第10001位质数是多少呢?
============================
第一次code:
1 import java.util.ArrayList; 2 import java.util.List; 3 4 public class Main 5 { 6 public static void main (String[] args) 7 { 8 System.out.println(binarySearch(prime(200000),10000)); 9 } 10 /** 11 * 对n个数进行求质数 12 * 所求出质数存到ArrayList数组中 13 * @param n 14 * @return 15 */ 16 public static List prime(int n) 17 { 18 List<Integer>list = new ArrayList<Integer>(); 19 for(int i=2;i<n;i++) 20 { 21 String b="YES"; 22 int [] a = new int[n]; 23 for(int j=2;j<i;j++) 24 { 25 a[j]=i % j; 26 if(a[j] == 0) 27 { 28 b="NO";break; 29 } 30 } 31 if(b.equals("YES")) 32 { 33 list.add(i); 34 } 35 } 36 return list; 37 } 38 /** 39 * 对ArrayList数组进行折半二查法查找 40 * @param x 41 * @param n 42 * @return 43 */ 44 public static int binarySearch(List x, int n) 45 { 46 int start = 0; 47 int end = x.size() - 1; 48 int mid = -1; 49 while (start <= end) 50 { 51 mid = (start + end) / 2; 52 if (mid == n) 53 { 54 return (int) x.get(mid); 55 } 56 else if (mid > n) 57 { 58 end = mid - 1; 59 } 60 else if (mid < n) 61 { 62 start = mid + 1; 63 } 64 } 65 return -1; 66 } 67 }
结果为:104743
时间效率:求出200000内的所有质数后,再检索出第10001位质数,所花时间为43638毫秒。