Mathijs - 1 year ago 60

C# Question

I debugged my code and everything works perfectly. But my code never writes to console for some reason.

Here is my code:

`long largest = 0;`

for (long i = 1; i < 600851475144; i++)

{

long check = 0;

for (long j = 1; j < i + 1; j++)

{

if ((i%j) == 0)

{

check++;

}

}

if (check == 2)

{

largest = i;

}

}

Console.WriteLine(largest);

Console.ReadKey();

Question: How do I write to console?

Answer Source

Your algorithm is too slow to complete in a reasonable time, so you need to come up with an alternative approach.

First, the algorithm has to stop checking the naive definition (two divisors). If you check all divisors up to square root of the number, and did not find any, the number is prime. Second, if you are looking for the largest prime in a range, start at the top of the range, go down, and stop as soon as you find the first prime. Third, there is no point to try even numbers.

Implementing these three changes will get your algorithm running in time.