欧拉计划(12)Highly divisible triangular number

来源:互联网 发布:php前台模板 编辑:程序博客网 时间:2024/05/01 05:50
【题目】

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: 优化计算约数的函数int GetCount(int n){int count=0;int end=(int)sqrt(n);//仅需计算 [1,sqrt(n)],在前半区间有约数m,则在后半区间也有约数n/m//此时约数个数加2for(int i=1;i<end+1;i++){if(n%i==0)count+=2;}//处理特殊情况if(end*end==n)count--;return count;}void test12_1(){int answer=0;for(int  i=1;;i++){answer+=i; //可以直接省去fun函数if( GetCount(answer) >=500)break;}cout<<answer<<endl;}
【答案】运行程序,可得本题答案为:76576500

0 0
原创粉丝点击