首页 > 其他 > 详细

素数距离问题

时间:2016-08-20 21:54:43      阅读:210      评论:0      收藏:0      [点我收藏+]

技术分享

之前的代码:

TLE:

 1 import java.util.Scanner;
 2 
 3 public class Main {
 4     
 5     public static void main(String[] args) {
 6         
 7         Scanner sc=new Scanner(System.in);
 8         
 9         int times=sc.nextInt();
10         while(times-->0){
11             int n=sc.nextInt();
12             
13             if(isPrime(n)){
14                 System.out.println(n+" 0");
15                 continue;
16             }
17                 
18             int shift=1;
19 
20             while(true){
21                  if(isPrime(n-shift)){
22                         System.out.printf("%d %d\n",n-shift,shift);
23                         break;
24                  }else if(isPrime(n+shift)){
25                     System.out.printf("%d %d\n",n+shift,shift);
26                     break;
27                 }
28             }
29         }
30         
31     }
32     
33     public static boolean isPrime(int n){
34         for(int i=2,end=(int) Math.sqrt(n);i<=end;i++){
35             if(n%i==0) return false;
36         }
37         return true;
38     }
39 
40 }

可能需要打表,于是使用打素数表:

//TODO

在网上看到一种号称线性复杂度的打表方法,先把手里的活干完再来仔细研究研究

素数距离问题

原文:http://www.cnblogs.com/cc11001100/p/5791243.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!