Project Euler Problem 12 asks to find the value of the first triangular number to have over 500 divisors, where the \$n\$th triangular number is \$\sum_{i=1}^{n} i\$.
The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be \$1 + 2 + 3 + 4 + 5 + 6 + 7 = 28\$. The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
1: 1 3: 1,3 6: 1,2,3,6 10: 1,2,5,10 15: 1,3,5,15 21: 1,3,7,21 28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.
I have the following code written in C#. I never had the patience to wait for the program to finish but the code shows the right answer because I tried the example on their website. My code has a very long runtime and I don't know what to do to optimize it. I've waited for like 5-6 minutes on a AMD 4x cores 3.10 GHz and nothing...
static void Main(string[] args) {
Stopwatch time = new Stopwatch();
time.Start();
int trianglenumber = 0;
int divizori = 0;
for (int i = 1; i < Int32.MaxValue; i++) {
int tempnumber = 0;
for (int j = 1; j < i; j++) {
tempnumber += j;
}
for (int k = 1; k < tempnumber+1; k++) {
if (tempnumber % k == 0) {
divizori++;
}
}
if (5 < divizori) {
trianglenumber = tempnumber;
break;
}
divizori = 0;
}
time.Stop();
double timp = time.ElapsedMilliseconds ;
Console.WriteLine(trianglenumber);
Console.Write("Runtime: " + timp/1000+ " seconds");
Console.ReadKey();
}
i < Int32.MaxValue
? \$\endgroup\$