当前位置:网站首页>Pat class B 1013 C language

Pat class B 1013 C language

2022-06-23 05:54:00 Octopus bro

1013. Prime number (20)


Make Pi It means the first one i Prime number . Now give two positive integers M <= N <= 104, Please export PM To PN All prime numbers of .

Input format :

Enter... On one line M and N, Separated by spaces .

Output format :

Output from PM To PN All prime numbers of , Every time 10 Two figures account for 1 That's ok , Separated by spaces , But there must be no extra space at the end of the line .

sample input :
5 27
sample output :
11 13 17 19 23 29 31 37 41 43
47 53 59 61 67 71 73 79 83 89
97 101 103


Ideas : from 2 Start , Add one to the count variable every time a prime number is encountered , On this basis, judge whether it is greater than M, Is less than N.

One 、 Starting variable

1.M、N

2.count, Prime count variables

3.enterFlag Newline count variable , When this value is 10 Output line wrap on , And will enterFlag Assign a new value to 1

Two 、 operation

1. Input M N

2. Start from 2 Traverse , Every time we encounter a prime number , Count variables plus one , Until the count variable is N-1

3. Count variables plus one , Then judge whether it is greater than M

3. Then judge whether line feed is required , If there is no need to judge whether there is a blank space

3、 ... and 、 Code

// Starting time 21:42 
#include "stdio.h"
#include "math.h"
int isPrime(int n);
int main()
{
	int M,N;
	M = N = 0;
	scanf("%d %d", &M, &N);
	int i;
	int count = 0;
	int enterFlag = 1;
        // Start from 2 Traverse , Every time we encounter a prime number , Count variables plus one , Until the count variable is N-1
       for(i = 2; count < N; i++)
	{
		if(isPrime(i))
		{
			count++;// Count variables plus one , Then judge whether it is greater than M
			if(count >= M)
			{
				if(enterFlag != 10)// Then judge whether line feed is required , If there is no need to judge whether there is a blank space 
				{
					if(count == N)
					{
						printf("%d",i);
						enterFlag++;
					}
					else
					{
					printf("%d ",i);
					enterFlag++;
					}
				}
				else 
				{
					printf("%d\n",i);
					enterFlag = 1;
				}
			}
		}
	}
	return 0;
}
int isPrime(int n)
{
	int ret = 1;
	int i = 2; 
	if(n == 2)
	{
		return ret;
	}
	int s = sqrt(n);
	for(i = 2; i <= s; i++)
	{
		if(n % i == 0)
		{
			ret = 0;
			break;
		}
	}
	return ret;
}


原网站

版权声明
本文为[Octopus bro]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206230410348259.html