PAT(Basic Level) 1013 数素数

在做完1007 素数对猜想,了解素数相关知识后,这题就非常简单啦。

1007中使用的筛子法在这并不适用,使用素数定义判断是否为素数即可。

这里我并不是完全按照素数定义写的判断函数,进行了细微的优化:

  1、只需判断除1,2,3,5,7之外的数中的奇数是否为素数;

  2、判断时判断它是否能被某奇数除尽即可;

  3、判断时注意循环条件:

            

  (摘自博客1007)

 1 #include<iostream>
 2 
 3 using namespace std;
 4 
 5 bool judge_prime(int n)
 6 {
 7     if(n==1) return 0;
 8     else if(n==2||n==3||n==5||n==7) return 1;
 9     else if(n%2==0) return 0;
10     else{
11         for(int i=3;i*i<=n;i+=2){
12             if(n%i==0) return 0;
13         }
14         return 1;
15     }
16 }
17 
18 int main(){
19      int M,N;
20      cin>>M>>N;
21      
22      int flag_M=0,count=0;
23      int print_flag=0;
24      int a=N-M+1;
25      for(int i=2;count<a;i++)
26      {
27         if(judge_prime(i))
28         {
29              flag_M++;
30              if(flag_M>=M&&a>1)
31             {    
32                 if(count==a-1){
33                     cout<<i;
34                     count++;
35                 } 
36                  else if(print_flag<9)
37                 {
38                      cout<<i<<" ";
39                      print_flag++;
40                     count++;                                  
41                 }                    
42                     
43                 else
44                 {
45                      cout<<i<<endl;
46                      print_flag=0;
47                      count++;
48                 }
49             }
50              
51             else if(flag_M>=M&&a==1)
52             {
53                  cout<<i;
54                  count++;
55             }
56             
57             else continue;
58         }
59     }
60      
61      return 0;
62 }

运行结果:

可喜可贺。

猜你喜欢

转载自www.cnblogs.com/stray-yang/p/13372594.html