Online Judge | Problem Set | Authors | Online Contests | User | ||||||
---|---|---|---|---|---|---|---|---|---|---|
Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest |
Re:贴Java代码。筛选后排序+二分查找 ,带注释In Reply To:贴Java代码。筛选后排序+二分查找 ,带注释 Posted by:haqishen at 2015-01-11 10:21:02 > //筛选后排序+二分查找 > import java.util.*; > > public class Main{ > static final int n = 250001; > > // nums用于进行筛选,Hprimes用于保存生成出来的Hprime > static boolean nums[] = new boolean[n]; > static ArrayList<Integer> Hprimes = new ArrayList<Integer>(); > > // 用筛选法生成Hprimes > static void generate_Hprimes(){ > for(int i = 0; i < n; i++) > nums[i] = true; > nums[0] = nums[1] = false; > > for(int i = 1; i < n; i++){ > // 第一个Hnumber > int n1 = 4*i + 1; > for(int j = 1; j <= i; j++){ > // 第二个Hnumber > int n2 = 4*j + 1; > // 两者相乘得到一个由2个Hnum构成的Hnum > int n3 = n1 * n2; > if(n3 > 4*n) break; > // 如果这个数还没有被筛选掉,则说明这个数是Hprime > if(nums[n3/4]){ > // 将这个数放入Hprimes > Hprimes.add(n3); > // 进行筛选 > for(int p = n3 * 1; p < 4*n; p += 4*n3){ > nums[p/4] = false; > } > } > } > } > } > public static void main(String[] args) { > Scanner s = new Scanner(System.in); > > // 生成Hprimes,然后升序排序 > generate_Hprimes(); > Collections.sort(Hprimes); > > while(true) > { > int h = s.nextInt(); > if(h==0) break; > > // 对于输入的数字进行二分查找,然后下标就是答案 > int l = 0, r = Hprimes.size()-1; > while(l<=r){ > int m = (l+r)/2; > if(Hprimes.get(m) > h){ > r = m - 1; > }else{ > l = m + 1; > } > } > System.out.println(h+" "+l); > } > } > } 不是prime,是semi Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator