(The Sieve of Eratosthenes) A prime integer is any integer that is evenly divisible only by itself and
1. The Sieve of Eratosthenes is a method of finding prime numbers. For example, 2, 3, 5 and 7 are
prime, but 4, 6, 8 and 9 are not.
Write a function that determines whether a number is prime.
Use this function in a program that determines and prints all the prime numbers entered
by the user.
Use an array to store all the values entered by the user.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Q210065
{
class Program
{
public static void SieveOfEratosthenes(int n,int[] values){
// initially assume all integers are prime
bool[] prime = new bool[n + 1];
for (int i = 0; i < n; i++) {
prime[i] = true;
}
for (int p = 2; p * p <= n; p++){
if (prime[p] == true)
{
for (int i = p * p; i <= n; i += p) {
prime[i] = false;
}
}
}
Console.WriteLine("The prime numbers are: ");
// Print all prime numbers
for (int i = 0; i < values.Length; i++)
{
if (values[i] >= 2) {
if (prime[values[i]] == true){
Console.Write(values[i]+ " ");
}
}
}
}
// Driver Code
public static void Main()
{
int n;
Console.Write("Enter n: ");
int.TryParse( Console.ReadLine(),out n);
int[] values=new int[n];
for (int i = 0; i < n; i++) {
Console.Write("Enter values[{0}]: ", i);
int.TryParse(Console.ReadLine(), out values[i]);
}
SieveOfEratosthenes(values.Max()+1, values);
Console.ReadLine();
}
}
}
Comments
Leave a comment