求最小的有500个约数的三角形数
原题来自Project Euler http://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?
我注意到三角形数的通项公式是(n+1)n/2,因此试图根据(n+1)、n的约数个数求出对应三角形数的约数个数,但是算法似乎有点问题,求指教。
我的思路是,n和n+1互质,因此他们各自的约数、约数的积都应该是乘积的约数。但是这样可能会有重复计算的问题。
还是说就应该暴力一点直接算?但数字又好像很大,可能会数据溢出……
#include <iostream>
using namespace std;
int main()
{
int n, i, dvsr;
int c1[3] = { 0, 0}, c2[3] = { 0, 0};
long int numb, count, numb1, count1;
const long int N = 1000000;
numb = 0;
count = 0;
for(n = 1;;n ++)
{
c2[0] =
c2[1] = 0;
for(i = 1;i <= n;i ++)
{
if(!(n%i))
{
c2[0] ++; //stands for the number of devisers
if(i%2)c2[1] ++; //stands for odd devisors
}
}
dvsr = c2[0]+c1[0]-1 //the sum of devisors
+c2[0]*c1[0]-3 //the product of devisors
-c2[1]-c1[1];
numb += n;
if(numb >= N)
{
count += N;
numb -= N;
}
if(dvsr >= 500)break;
c1[0] = c2[0];
c1[1] = c2[1];
}
numb1 = count1 = 0; //to check if the numb is correct
for(i = 0;i <= n;i ++)
{
numb1 += i;
if(numb1 > N)
{
numb1 -= N;
count1 ++;
}
}
cout << "Hello world!" << endl
<< n << endl << count << endl << numb << endl << dvsr << endl
<< numb1 << endl << count1 << endl;
return 0;
}