我正在解决一项任务 - 用户正在输入 3 个数字,a, b, c
. 目标是找出是否可以c
求和a
和b
。在每个步骤中都允许添加a
tob
和b
to a
。我需要确定输入的数字是否可行。输入的数字在0
和之间10^18
。下面是我的代码,用递归完成。
解决任务的示例a=4 b=6 c=38
:
a=4 b=10
a=14 b=10
a=14 b=24
a=38 b=24 print YES
我下面的代码对于低数字做得很好,但我认为我正在失去与更大数字的战斗......我添加了一些评论来说明什么部分正在做什么。
我需要帮助的是,我需要它更好、更快地工作,我不知道如何进一步优化它。
//the function that I'm using
int task(long long int a, long long int b, long long int c, long long int d, int p)
{ //a, b and c are long long integers that are submited by the user, d is the sum of
//the unchanged a and b, and p is a flag
if(!a && !b && c) return 0; //0+0 will never get to 1
if(c==d) return 1; //if I get with c to d, it is confirmed yes,
//did the math with a pen :)
if(c<d || c<=0) // I thought this is a nice case to stop
{
return 0;
}
if(p==1)
{
if(a>c) return 0; //if the flag p is one, that means i changed a,
//so compare a
}
if(p==2)
{
if(b>c) return 0; //if p is two, i changed b so compare b
}
if(c-d>0) return task(a+b, b, c-b, d, 1)||task(a, b+a, c-a, d, 2);
//recursion call with OR operator so every step is checked
}//one part is a=a+b b=b c=c-b, i decrement c so fewer steps are needed,
//the other part is when i add a to b
int main()
{
long long int a,b,c;
scanf("%I64d%I64d%I64d",&a,&b,&c); //scaning
int p; //the flag for the first numbers
if(a>b) p=1; //i dont know if i need this step at all xD
else p=2; //but to make sure
if((a==1 || b==1) && c) printf("YES"); //a=1 b=1 and c>=1 means i can get to c,
//even with a+b+b+b..
else if(a==c || b==c) printf("YES"); //if one of the numbers are already same
//with c, no need to check
else if(task(a,b,c,a+b,p)) printf("YES"); //if the function returns 1, print YES
else printf("NO"); //or print NO
return 0;
}