一個有趣的問題:php
A triplet of positive integers (a,b,c) is called a Cardano Triplet if it satisfies the condition:html
For example, (2,1,5) is a Cardano Triplet.c++
There exist 149 Cardano Triplets for which a+b+c 1000.算法
Find how many Cardano Triplets exist such that a+b+c 110,000,000.windows
首先能夠把問題的表達式能夠化成:分佈式
8a^3 + 15a^2 + 6a - 1 = 27b^2*c函數
而後使用窮舉法遍歷a,b,c能夠取的全部值,判斷是否知足上述表達式:post
int CardanoTriplets1(int Max)url
{spa
long a, b, c;
long count = 0;
for(a = 1; a < Max; a++)
{
for(b = 1; b < Max - a; b++)
{
for(c = 1; c <= Max - a - b; c++)
{
if((8*a*a*a + 15*a*a + 6*a - 1) == 27*b*b*c)
{
count++;
}
}
}
}
return count;
}
能夠根據問題的性質對算法稍做改進:
第一,能夠證實a知足a = 2 (mod 3)或者2a = 1 (mod 3),證實略
第二,給定a的值之後,有:
b^2*c = S
b + c = K
S和K都是a的表達式,從上面兩式能夠求出b的一個下界和上界:
4 * S / K^2 <= b <= S^0.5
由此能夠給出程序:
int CardanoTriplets2(int Max)
{
long a, b, c;
long count = 0;
double S, K, b_min, b_max;
double t;
for(a = 1; a < Max; a++)
{
if(a % 3 == 2)
{
K = Max - a;
t = 1.0 - 2.0 * a;
S = a * a - t*t*t/27.0;
b_min = 4.0 * S / K / K - 1;
b_max = sqrt(S) + 1;
if(b_min < 1) b_min = 1;
if(b_max > K) b_max = K;
for(b = (long)b_min; b <= (long)b_max; b++)
{
c = (long)S / b / b;
if(c >= 1 && (b * b * c) == S && (b + c) <= K)
{
//cout<<"("<<<","<<<","<
count++;
}
}
}
}
return count;
}