I am trying to write a function for creating a prime factors list. For this - I am using a recursive function. Here are the calls:
private int Problem003()
{
//The prime factors of 13195 are 5, 7, 13 and 29.
//What is the largest prime factor of the number 600851475143 ?
return GeneratePrimeFactorsList(15).Last();
}
private List<int> GeneratePrimeFactorsList(int n)
{
List<int> _primefactors = new List<int>();
_primefactors.Add(2);
int i = 3;
while(i <= n)
{
if (CheckIfIntIsPrime(_primefactors, i))
{
_primefactors.Add(i);
}
i=i+2;
}
return _primefactors;
}
private bool CheckIfIntIsPrime(List<int> _primefactors, int i)
{
if (_primefactors.Count() == 0)
{
return true;
}
else
{
if(i % _primefactors.First() != 0)
{
_primefactors.Remove(_primefactors.First());
return CheckIfIntIsPrime(_primefactors, i);
}
else
{
return false;
}
}
}
The problem is that, when I am calling for CheckIfIntIsPrime(List, i), which have bool return type - it modifies the List. That means, that after the check - the passed argument into the GeneratePrimeFactorsList(int) is getting empty after each while loop iteration.
The CheckIfPrime function works correctly, but modifies the passed argument, when it should not - I dont relate them.
Very strange case, but I feel, that I missing knowledge about some of the List properties.