Problem Description
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
思路
因为刚开始没思路,所以试着写了个小程序,找出了符合条件的几种情况
发现 当 t=4,14,52,194 的时候满足题目要求,然后试图寻找数据之间的关系,可以发现t[i]=4*t[i-1]-t[i-2] (t>=2)
接下来就是递推,大数运算
代码
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define MAX 1000
char ans[MAX][MAX]={"0","4","14","52","194"};
void Multiplication(int pos)
{
int x[MAX],r[MAX],i,k;
int l=strlen(ans[pos-1]);
memset(r,0,sizeof(r));
for(i=l-1,k=0;i>=0;i--,k++)
x[k]=ans[pos-1][i]-'0';
for(i=0;i<l;i++)
r[i]=x[i]*4;
for(i=0;i<l+5;i++)
{
if(r[i]>=10)
{
r[i+1]+=r[i]/10;
r[i]%=10;
}
}
i=l+5;
while(!r[i])
{
i--;
}
ans[pos][i+1]='\0';
int index=0;
while(i>=0)
{
ans[pos][index]=r[i]+'0';
i-=1; index+=1;
}
}
void Substraction(int pos)
{
int len_re=strlen(ans[pos]);
int len_Minus=strlen(ans[pos-2]);
int i,k,A[MAX],B[MAX];
memset(A,0,sizeof(A));
memset(B,0,sizeof(B));
for(i=len_re-1,k=0;i>=0;i--,k++)
A[k]=ans[pos][i]-'0';
for(i=len_Minus-1,k=0;i>=0;i--,k++)
B[k]=ans[pos-2][i]-'0';
for(i=0;i<len_re;i++)
{
A[i]-=B[i];
if(A[i]<0)
{
A[i]+=10;
A[i+1]--;
}
}
len_re+=2;
while(!A[len_re])
{
len_re-=1;
}
ans[pos][len_re+1]='\0';
int index=0;
while(len_re>=0)
{
ans[pos][index]=A[len_re]+'0';
len_re-=1; index+=1;
}
}
void cal()
{
for(int i=5;i<=300;i++)
{
Multiplication(i);
Substraction(i);
}
}
int compare(char *str,int pos)
{
int l_str=strlen(str);
int l=strlen(ans[pos]);
if(l_str<l)
return 1;
else if(l_str>l)
return 0;
for(int i=0;i<l;i++)
{
if(str[i]>ans[pos][i])
return 0;
else if(str[i]<ans[pos][i])
return 1;
}
return 1;
}
int main()
{
int T;
scanf("%d",&T);
cal();
while(T--)
{
char str[MAX];
scanf("%s",str);
for(int i=1;i<=300;i++)
{
if(compare(str,i))
{
printf("%s\n",ans[i]);
break;
}
}
}
return 0;
}
//大数+数学规律