Ray's playground

 

Project Euler 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?

 1 #include <iostream>
 2 using namespace std;
 3 
 4 int GetDivisorsCount(long long num)
 5 {
 6     if(num < 1)
 7     {
 8         return 1;
 9     }
10 
11     int count = 1;
12     int factor = 2;
13     long long n = num;
14     int i, t;
15     while(n > 1)
16     {
17         if(n % factor == 0)
18         {
19             t = 1;
20             while(n % factor == 0)
21             {
22                 t++;
23                 n /= factor;
24             }
25             count *= t;
26         }
27         factor++;
28     }
29 
30     return count;
31 }
32 
33 int main()
34 {
35     long long sum = 0;
36     long long i = 1;
37     while(GetDivisorsCount(sum) < 500)
38     {
39         sum = sum + i++;
40         cout << sum << endl;
41     }
42 
43     cout << sum;
44     cin.get();
45 }

posted on 2011-03-10 21:19  Ray Z  阅读(196)  评论(0编辑  收藏  举报

导航