I am trying to do Project Euler problem 12, and I have the right code, but it's really slow.

This is the description of the problem (projecteuler.net):

Quote

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.

What is the value of the first triangle number to have over five hundred divisors?

This is my code:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; namespace Project_Euler { class Program { static void Main(string[] args) { int count = 1; double triangleNumber; ArrayList divisors = new ArrayList(); while (true) { triangleNumber = 0; divisors.Clear(); for (int i = 1; i <= count; i++) { triangleNumber += i; } for (int i2 = 1; i2 <= triangleNumber; i2++) { if (triangleNumber % i2 == 0) divisors.Add(i2); } Console.Clear(); Console.WriteLine("Triangle number checked: " + triangleNumber.ToString()); Console.WriteLine("\nDivisors: " + divisors.Count.ToString()); if (divisors.Count > 500) break; count++; } Console.ReadKey(); } } }

This code works (I've tried it with the example). The thing is, it's really slow.

I've let this code run for ~40 minutes and it didn't finish.

Programming is just a hobby of mine, so I didn't really learn how to optimize code.

Could anyone tell me how I could do this, or where I can find information on code optimization for these kind of subjects?

Thanks in advance.