原题链接:http://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?
题目大意是:
三角形数序列是由对自然数的连加构造而成的。所以第七个三角形数是1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. 那么三角形数序列中的前十个是:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
下面我们列出前七个三角形数的约数:
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
可以看出28是第一个拥有超过5个约数的三角形数。
那么第一个拥有超过500个约数的三角形数是多少?
解法1:
从第一个三角形数开始,计算每个三角形数的约数个数,直到某个三角形数具有超过500个约数为止。而计算约数个数的方法是:先初始化个数为2,即1和它本身;然后从i=2开始,到这个数的平方根的向下取整,能被i整除则个数加2;如果这个数是个平方数,我们需要将个数减去1。
php代码如下所示:
$over_num = 500; $count_of_divisors = 0; $sum = 0; $i = 1; function get_divisors_num($number){ $sqrt_root = floor(sqrt($number)); $num = 2; for($i=2;$i<=$sqrt_root;$i++){ if($number%$i==0){ $num+=2; } } if(pow($sqrt_root,2)==$number){ $num -=1; } return $num; } while($count_of_divisors<=$over_num){ $sum += $i; $i++; $count_of_divisors = get_divisors_num($sum); } echo $sum,"\n";
注:题目的中文翻译源自http://pe.spiritzhang.com