C#版 - PAT乙级(Basic Level)真题 之 数素数_牛客网
在线提交: https://www.nowcoder.com/pat/6/problem/4079
题目描述
令 表示第i个素数。现任给两个正整数M <= N <= 10000,请输出 到 的所有素数。
输入描述:
输入在一行中给出M和N,其间以空格分隔。
输出描述:
输出从 到 的所有素数,每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
思路:
使用筛法(厄拉多塞Eeatosthese - SieveMethod法)来求素数。
然后按要求的格式输出素数即可~
已AC代码:
using System;
namespace Pat1_PrintPrime
{
public class Solution
{
public const int N = 200005; // Set a szie enough to store.
public void PrintPrimes(int m, int n)
{
int[] primes = new int[N];
bool[] isDelete = new bool[N];
int index = 0;
int count = 0;
for (int i = 2; i * i < N; i++)
{
if (!isDelete[i])
{
for (int j = i; i * j < N; j++)
{
isDelete[i * j] = true;
}
}
}
for (int i = 2; i < N; i++)
{
if (isDelete[i] == false)
{
primes[index++] = i;
}
}
for (int i = m; i <= n; i++)
{
Console.Write(primes[i - 1]);
if (++count % 10 == 0 && i != n)
Console.WriteLine(); // new line
else if (i != n)
Console.Write(" ");
}
}
}
class Program
{
static void Main(string[] args)
{
string sb;
while ((sb = Console.ReadLine()) != null)
{
string[] s = sb.Split();
int m = int.Parse(s[0]);
int n = int.Parse(s[1]);
var sol = new Solution();
sol.PrintPrimes(m, n);
}
}
}
}
Rank:
可参考笔者之前的文章:
https://blog.csdn.net/lzuacm/article/details/80629723