▼页尾

[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?

寻找第一个因数个数超过500的三角数

计算一个数因数个数的方法,最常见的分解质因数的方法

但编程的时候,寻找质因数是很烦琐的事情

所以我们直接用整除判断该数所有的因数

显然,如果所以小于sqrt(该数)的数中有n个因数,那么这个数的因数有2*n个。

如果该数恰是平方数,那么该数有因数2 *n+1个

#include <iostream>
using namespace std;

int getDivisorNumber(int n){
int number=0;
int divisor = 1;
int triangle = n*(n+1)/2;
while(divisor*divisor < triangle){
if(triangle%divisor == 0){
number
++;
}
divisor
++;
}

if(divisor*divisor == triangle)
return 2*number+1;
else
return 2*number;
}

int main(){
int n=1;
while(getDivisorNumber(n) <= 500){
n
++;
}
cout
<< n*(n+1)/2 << endl;
return 0;
}


posted @ 2011-02-24 10:22  xiatwhu  阅读(355)  评论(0编辑  收藏  举报
▲页首
西