## Thursday, October 20, 2011

### Triangle Numbers

I use a website called Project Euler (www.projecteuler.net) to find problems to work on. Problem 12 on the website asks you to find the first triangle number with 500 or more divisors. SPOILER ALERT: The answer is at the very bottom of this post. Click on Read More to see it. Here is the code I used to figure it out:

``` /* Chuck Woodraska Program Description - projecteuler.net Problem 12 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. What is the value of the first triangle number to have over five hundred divisors? */ #include <iostream> #include <math.h> using namespace std; int main() { // start with the 1st triangle number int start = 1; int i = 2; // count for getting the next triangle number (1 + 2 + 3 ...) int count = 0; // count for how many divisors the particular triangle number has // Just trying to find the first triangle number to have 500 divisors while(start < 1000000000) { int temp = 1; // reset temp to start the test divisor at 1 // finding all the divisors while(temp < sqrt(start)) { //cout << "Test mod: " << start % temp << endl; // checking if temp is a divisor if(start % temp == 0) { ++count; } ++temp; } // double the number of divisors because they come in pairs and we only found the 1st half // NOTE: if the number is a perfect square this program will not correctly give the number of divisors // it will give one to many because it will be counting the same number twice count = count * 2; // print out the triangle number and its number of divisors // cout << "Triangle number is: " << start << endl; // cout << "Divisor total: " << count << endl; // quit once we find one with more than 500 if(count > 500) { cout << "Triangle number is: " << start << endl; cout << "Divisor total: " << count << endl; exit(0); } // find the next triangle number start = start +i; ++i; count = 0; } return 0; }```

`The answer:`
`76576500`