数素数

 

数素数

//需要注意两点:一是Pm和Pn表示的是素数个数的区间,而不是在这两个数范围内找素数;

//二是输出情况分三种,首先是未满10个数一行的中间每个数输出中间都有空格,再者是满10个数时要进行换行                       // 操作,最后是输出的最后一个数如果不是在输出行的第十个数,则其后面不能有空格。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

 

public class Main {

    public static void main(String[] args) throws IOException{

        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

        String str=br.readLine();

        String[] s1=str.split(" ");

        int Pm=Integer.parseInt(s1[0]);

        int Pn=Integer.parseInt(s1[1]);

        int count1=1;//计数素数个数

        int count2=1;//计数素数数是否为10个

        boolean flag;

        for(int i=2;count1<=Pn;i++){

            if(flag=isPrime(i) && count1<Pm){

                count1++;

                continue;

            }

            if(flag=isPrime(i)){

                if(count2%10!=0 && count1!=Pn){

                    System.out.print(i+" ");

                    count2++;

                    count1++;

                }else if(count2%10==0 && count1!=Pn){

                    System.out.println(i);

                    count2=1;

                    count1++;                  

                }else if(count2%10!=0 && count1==Pn){

                    System.out.print(i);

                    count1++;

                    count2++;

                }

            }

                             

        }

    }

     

    private static boolean isPrime(int num) {

         

        boolean flag=true;

        if(num<2)

            return false;

        else{

            for(int i=2;i<=Math.sqrt(num);i++){

                if(num%i==0){

                    flag=false;

                    break;

                }

            }          

        }

        return flag;

    }  

}

  •