PTA 7-3 可逆素数 (15分)

请从小到大输出所有4位数的可逆素数。可逆素数指: 一个素数将其各位数字的顺序倒过来构成的反序数也是素数。

输入格式:

输出格式:

一行中以空格间隔输出可逆素数,行尾无空格。行末尾无多余空格和换行

输入样例:

 

输出样例:



作者: 陈英
单位: 南昌航空大学
时间限制: 100 ms
内存限制: 64 MB
代码长度限制: 16 KB
 
 
 
 1 public class Main {
 2     public static void main(String[] args) {
 3         int sum=0;
 4         for(int i=1000;i<=9999;i++) {
 5             if(sss(i)==1) {
 6                 int gw=i%10;
 7                 int sw=i%100/10;
 8                 int bw=i%1000/100;
 9                 int qw=i/1000;
10                 if(sss(gw*1000+sw*100+bw*10+qw)==1) {
11                     if(sum==0)System.out.print(i);
12                     else System.out.print(" "+i);
13                     sum=1;
14                 }
15             }
16         }
17     }
18 
19     private static int sss(int x) {
20 
21         int i,flag=1;
22         for(i=2;i<=Math.sqrt(x);i++) {
23             if(x%i==0) {
24                 flag=0;//不是素数
25                 break;
26             }
27         }
28         if(flag==1)return 1;//是素数
29         else return 0;
30     }
31 }
这个题卡时间过 凭运气过 有时候用时少 有时候就超了。甚至删除个空行 本来不超时 一删除就超时了。加注释都超时。
 

猜你喜欢

转载自www.cnblogs.com/Flyfishy/p/12163863.html