I want to create a program in C# 2005 which calculates prime factors of a given input. i want to use the basic and simplest things, no need to create a method for it nor arr
This version lists all the factors as an explicit formula:
static void Main(string[] args)
{
Console.WriteLine("Please enter your integer (0 to stop): ");
int a = int.Parse(Console.ReadLine());
while(a>0)
{
List primeFactors = PrimeFactors(a);
LogFactorList(primeFactors);
a = int.Parse(Console.ReadLine());
}
Console.WriteLine("Goodbye.");
}
///
/// Find prime factors
///
public static List PrimeFactors(int a)
{
List retval = new List();
for (int b = 2; a > 1; b++)
{
while (a % b == 0)
{
a /= b;
retval.Add(b);
}
}
return retval;
}
///
/// Output factor list to console
///
private static void LogFactorList(List factors)
{
if (factors.Count == 1)
{
Console.WriteLine("{0} is Prime", factors[0]);
}
else
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < factors.Count; ++i)
{
if (i > 0)
{
sb.Append('*');
}
sb.AppendFormat("{0}", factors[i]);
}
Console.WriteLine(sb.ToString());
}
}