PAT 乙级 1013.数素数 C++/Java

题目来源

令 Pi​​ 表示第 i 个素数。现任给两个正整数 MN104​​,请输出 PM​​ 到 PN​​ 的所有素数。

输入格式:

输入在一行中给出 M 和 N,其间以空格分隔。

输出格式:

输出从 PM​​ 到 PN​​ 的所有素数,每 10 个数字占 1 行,其间以空格分隔,但行末不得有多余空格。

输入样例:

5 27

输出样例:

11 13 17 19 23 29 31 37 41 43
47 53 59 61 67 71 73 79 83 89
97 101 103

分析:

将1 - PN的素数都求出来,即:记录素数的个数count,当count等于第PN的时候,循环结束

 

C++实现

 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
 4 
 5 
 6 bool isprime(int n)
 7 {
 8     for (int i = 2; i * i <= n; ++i)
 9     {
10         if (n % i == 0)
11         {
12             return false;
13         }
14     }
15     return true;
16 }
17 
18 int main()
19 {
20     int num = 2, N, M;
21     int count = 0;    //记录素数个数
22     vector<int> v;
23     cin >> M >> N;
24 
25     while (count < N)
26     {
27         if (isprime(num))
28         {
29             ++count;
30             if (count >= M)
31             {
32                 v.push_back(num);
33             }
34         }
35         ++num;
36     }
37 
38     count = 0;
39     for (int i = 0; i < v.size(); ++i)
40     {
41         ++count;    //控制输出行数
42         if (count % 10 != 1)
43         {
44             cout << " ";
45         }
46         cout << v[i];
47         if (count % 10 == 0)
48         {
49             cout << endl;
50         }
51     }
52 
53 
54     return 0;
55 }

 

Java实现:

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

 

posted @ 2019-10-06 16:52  47的菠萝~  阅读(197)  评论(0编辑  收藏  举报