A triangle is a Heron’s triangle if it satisfies that the side lengths of it are consecutive integers t−1, t, t+ 1 and thatits area is an integer. Now, for given n you need to find a Heron’s triangle associated with the smallest t bigger
than or equal to n.
Input
The input contains multiple test cases. The first line of a multiple input is an integer T (1 ≤ T ≤ 30000) followedby T lines. Each line contains an integer N (1 ≤ N ≤ 10^30).
Output
For each test case, output the smallest t in a line. If the Heron’s triangle required does not exist, output -1.
Sample Input
4
1
2
3
4
Sample Output
4
4
4
4
每给出一个数n, 求一个大于等于n的数x,
要求: x-1, x, x+1可构成一个三角形
首先暴力枚举出较小的结果
得到4,14,52,194…一系列数字
由此可以得到规律a[n] == a[n-1]*4 - a[n-2]
由于该数列数字较大, 可知涉及大数乘法和大数减法
打表后将输入的n与表中数字对比即可
#include
#include
#include
#define MAXT 200
#define MAXN 50
#define CON 4
char reserve[MAXT][MAXN];
int lenfin;
void BigNumOpe( char* small, char* big, int m)
{
int i, j, k;
int lens, lenb, lensum, lent;
char result[MAXN] = {0};
char temp[MAXN] = {0};
char t[MAXN] = {0};
lenb = strlen(big);
lensum = lenb + 1;
lens = strlen(small);
for( i=0; i<lenb; i++)
{
temp[i] = (big[lenb-i-1]-'0') * 4;
}
for( i=0; i<lensum; i++)
{
temp[i+1] += temp[i] / 10;
temp[i] %= 10;
}
// lent = strlen(temp); 错误, 出现0 会自动减少
if( temp[lensum-1]>0)
{
lent = lensum;
}
else
{
lent = lensum-1;
}
for( i=0; i<lens; i++)
{
t[i] = small[lens-i-1] - '0';
}
for( i=0; i<lent; i++)
{
if( temp[i]< t[i])
{
temp[i] += 10;
temp[i+1] --;
}
result[i] = temp[i] - t[i];
}
for( i=0; i<lent; i++)
{
reserve[m][i] = result[lent-i-1] + '0';
}
reserve[m][i] = '\0';
lenfin = strlen(reserve[m]);
// puts(reserve[m]);
}
int compare(char *x, char *y)
{
int lenx = strlen(x);
int leny = strlen(y);
int k = -1, i;
if( lenx>leny)
{
k = 1;
}
else if(lenx < leny)
{
k = -1;
}
else if( lenx == leny)
{
for( i=0; i<lenx; i++)
{
if( x[i] - y[i] > 0)
{
k = 1;
break;
}
else if( x[i] - y[i] < 0)
{
k = -1;
break;
}
}
}
return k;
}
int main(void)
{
int i, j, k, t;
char x[MAXN];
strcpy(reserve[0], "4");
strcpy(reserve[1], "14");
for( i=2; lenfin<32; i++)
{
BigNumOpe( reserve[i-2], reserve[i-1], i);
}
scanf("%d", &t);
while(t--)
{
memset(x, 0, sizeof(x));
scanf("%s", x);
for( i=0; ;i++)
{
k = compare(x, reserve[i]);
if( k<=0)
{
break;
}
}
puts(reserve[i]);
}
return 0;
}