Answer to Question #210065 in C# for Nick Oliver

Question #210065

(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.


1
Expert's answer
2021-06-23T17:05:33-0400
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();
        }
    }
}






Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS