I have the following peace of code, that factors an int
to prime numbers:
private static IEnumerable<int> Factor(int input)
{
IList<int> result = new List<int>();
while (true)
{
var theSmallestDivisor = GetTheSmallestDivisor(input);
if (theSmallestDivisor == 0)
{
result.Add(input);
return result;
}
result.Add(theSmallestDivisor);
input = input/theSmallestDivisor;
}
}
I'm looking for hints on how to improve it, possibly using LINQ.
Here's an iterator version:
private static IEnumerable<int> Factor(int input)
{
while (true)
{
var theSmallestDivisor = GetTheSmallestDivisor(input);
if (theSmallestDivisor == 0)
{
yield return input;
yield break;
}
yield return theSmallestDivisor;
input = input / theSmallestDivisor;
}
}
LINQ would only make this code less readable in that particular case.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments