using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace PrimeFactorisation
{
class Program
{
static int Main(string[] args)
{
Eratosthenes eratosthenes = new Eratosthenes();
bool ok = true;
while (ok)
{
if ((args == null) || (args.Length < 1))
{
Console.WriteLine("Syntax: primes InputFile ");
Console.ReadKey();
return 1;
}
string InFile = args[0];
//
Console.WriteLine("Reading from:{0}", InFile);
try
{
string[] numbersList = File.ReadAllLines(InFile);
foreach (string number in numbersList)
{
int toFactorise;
ok = int.TryParse(number, out toFactorise);
if (ok && toFactorise >= 2)
{
StringBuilder factorList = new StringBuilder();
foreach (int factor in GetPrimeFactors(toFactorise, eratosthenes))
{
if (factorList.Length == 0)
factorList.Append("Prime factor(s): ");
else
factorList.Append(", ");
factorList.Append(factor);
}
Console.WriteLine(factorList);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadKey();
return 2;
}
Console.WriteLine("Press Enter To Continue");
Console.ReadKey();
return 0;
}
}
private static IEnumerable<int> GetPrimeFactors(int value, Eratosthenes eratosthenes)
{
List<int> factors = new List<int>();
foreach (int prime in eratosthenes)
{
while (value % prime == 0)
{
value /= prime;
factors.Add(prime);
}
if (value == 1)
break;
}
return factors;
}
}
}
Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.
”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.
Our community of experts have been thoroughly vetted for their expertise and industry experience.