Highly divisible triangular number
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?
此题刚开始不敢尝试,因为做过了,超时了,等了好久,还没出来结果。所以做到了第16题,又做了POJ的一些题目,然后对记忆化递归了解了才写了这道题。
#include <iostream>
#include <map>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
int cmp(int n)
{
if(n==1) return 1;
int sum=cmp(n-1)+n; //直接记住结果,就不会超时了。
return sum;
}
int abc(int n)
{
int i,sum=0;
for(i=1;i<=sqrt(n*1.0);i++)
if(n%i==0) sum++; //虽然用了sqrt,但是还是超过了1秒,这个用不了记忆化,所以时间还是有点多。
return sum;
}
int main()
{
int i;
for(i=1000;;i++)
if(abc(cmp(i))>=250) {cout<<cmp(i)<<endl;break;} //因为sqrt之前的就知道了总共的因子了,乘以2就是其因子数。
return 0;
}