代码
x
=
x
*
2
;
/* n(1+n)/2 = x */
n = ( int )sqrt(x); /* a*b =c^2 then a <= c <= b, so n <= sqrt(2x) <= n+1 */
for (; n >= 2 ; n -- )
{
if (x % n)
continue ;
a1 = x / n - n + 1 ;
if (a1 % 2 == 0 )
{
a1 /= 2 ;
show(a1, n);
showed = 1 ;
}
}
/* n(1+n)/2 = x */
n = ( int )sqrt(x); /* a*b =c^2 then a <= c <= b, so n <= sqrt(2x) <= n+1 */
for (; n >= 2 ; n -- )
{
if (x % n)
continue ;
a1 = x / n - n + 1 ;
if (a1 % 2 == 0 )
{
a1 /= 2 ;
show(a1, n);
showed = 1 ;
}
}
补充下思想:很简单,先算出可能序列的最大长度n
然后枚举每个n值,每个数位a, a+1, a+2, ..., a+(n-1),倒过来求a是否存在