/* * Created by SharpDevelop. * User: Admin * Date: 11/10/2021 * Time: 6:28 AM * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Diagnostics; namespace SimplePrimes { class Program { public static void Main(string[] args) { //bool[] nums; byte[] nums; int n, m, lim; Stopwatch elapsed; string yorn; Console.WriteLine("This program will search for prime numbers using a simple algorithm . . ."); Console.Write("Enter max limit # and press ENTER (leave blank for default): "); lim = Convert.ToInt32("0" + Console.ReadLine()); // WE HAVE TO PUT THE 0 IN FRONT TO FORCE STUPID C# TO NOT HAVE ERROR IF INPUT IS BLANK... // C# SHOULD RETURN 0 FOR A BLANK STRING AND ONLY EXCEPTION ON NULL STRING, BUT I DIDN'T DESIGN THIS :P if (lim == 0) lim = 100000000; elapsed = new Stopwatch(); elapsed.Start(); //nums = new bool[lim + 1]; nums = new byte[lim + 1]; for (n = 2; n < Math.Sqrt(lim); n++) { if (nums[n] == 0) { m = n * n; while (m <= lim) { nums[m] = 1; m += n; } } } elapsed.Stop(); Console.WriteLine("It took " + (elapsed.ElapsedMilliseconds / 1000.0).ToString() + " seconds to complete."); Console.Write("Do you want to print the results (Y/N)? "); yorn = Console.ReadLine(); if (yorn == "Y" || yorn == "y") { m = 0; for (n = 2; n <= lim; n++) { if(nums[n] == 0) { Console.WriteLine(n.ToString()); m++; } } Console.WriteLine("Total primes = " + m.ToString()); Console.WriteLine(""); Console.Write("Press any key to end . . . "); Console.ReadKey(true); } } } }