I am new to programming and a friend of mine suggested that I should do the exercise on project Euler to get better in it. I encountered a problem on question 3:
"The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ?"
Now here's my solution:
class Program
{
static void Main(string[] args)
{
long number = 600851475143;
bool prime = true;
for (long i = 3; i <= number; i++)
{
for (long n = 2; n < i; n++)
{
if (i % n == 0)
{
prime = false;
break;
}
}
if (prime)
{
if (number % i == 0)
{
Console.WriteLine(i);
}
}
prime = true;
}
Console.ReadKey();
}
}
Now, while i did get the correct answer (which is 6857) Ive found my method very inefficient. If you'll run my code you'll see that it'll still run after more than 2 minuets... My question is how can I write a more efficient/faster code for this?