35
1
using System;
2
3
public class Program
4
{
5
public static void Main()
6
{
7
Console.WriteLine("Tìm số nguyên tố sử dụng thuật toán Sàng Eratosthenes");
8
int n;
9
Console.WriteLine("Nhập vào số cần tìm số nguyên tố nhỏ hơn:");
10
n = int.Parse(Console.ReadLine());
11
bool [] a = new bool[n+1];
12
//Khởi tạo mảng khởi tạo ban đầu đều là số nguyên tố
13
14
15
for(int i=2; i<=n;i++)
16
a[i] = true;
17
//Tìm số nguyên tố
18
for(int i=2; i<Math.Sqrt(n);i++)
19
{
20
if(a[i])
21
{
22
int j = (int)Math.Pow(i,2);
23
while(j <=n)
24
{
25
a[j] = false;
26
j += i;
27
}
28
}
29
}
30
Console.WriteLine("Các số nguyên tố là:");
31
for(int i=2; i<=n;i++)
32
if(a[i])
33
Console.Write("{0}, ",i);
34
}
35
}
Cached Result