c++数列:1,2,4,2,3,6,12,6,3,....求第n项值(递归)
这道题我想了好久,没想出来,哪位大神能帮帮我?(我刚学c++)
代码也能贴出来吗?
c++数列:1,2,4,2,3,6,12,6,3,....求第n项值(递归)
这道题我想了好久,没想出来,哪位大神能帮帮我?(我刚学c++)
代码也能贴出来吗?
#include <stdio.h>
int fun(int n,int *x,int *y)
{
int sum = 0,i;
int size = 0;
int dd = 1;
for (i = 1; i <= (*x);i++)
{
sum += (2*i-1);
}
if (sum == n)
{
*y = 2*(*x) -1;
return (*x);
}else if (sum > n)
{
(*y) = n - (sum - (2 * (*x) -1));
size = 2* (*x) -1;
dd = (*x); //第x行的第一个数
for (i = 2; i <= (*y);i++)
{
if(i <= (*x))
dd *= 2;
else
dd /= 2;
}
return dd;
}else
{
(*x)++;
return fun(n,x,y);
}
}
int main()
{
int n; //n项(从第1项开始)
int row = 1,col = 0;
int val;
row = 1;
col = 0;
printf("请输入n:");
scanf("%d",&n);
val = fun(n,&row,&col);
printf("第%d项是:%d\n",n,val);
return 0;
}