C# Prime Numbers Generator
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class PrimeNumbers
{
static void Main()
{
Console.Write("Please enter a number to generate prime numbers: ");
var ipVal = Convert.ToInt64(Console.ReadLine());
var primeNumbers = GetPrimeNumbersUpTo(ipVal);
PrintPrimeNumbers(primeNumbers, ipVal);
Console.ReadLine();
}
private static void PrintPrimeNumbers(List<long> primeNumbers, long range)
{
Console.WriteLine();
Console.WriteLine("Prime numbers between 2 to " + range);
foreach (long item in primeNumbers)
{
Console.WriteLine(item);
}
}
private static List<long> GetPrimeNumbersUpTo(long ipVal)
{
var primeList = new List<long>();
for (long value = 2; value <= ipVal; value++)
{
if (IsPrimeNumber(value))
{
primeList.Add(value);
}
}
return primeList;
}
private static bool IsPrimeNumber(long inputValue)
{
if (inputValue == 0 || inputValue == 1)
{
return false;
}
if (inputValue == 2)
{
return true;
}
var roundedVal = (long)Math.Round(Math.Sqrt(inputValue));
for (long i = 2; i <= roundedVal; i++)
{
if (inputValue % i == 0)
{
return false;
}
}
return true;
}
}
}
No comments:
Post a Comment