用递归求第N项的值

题目

用递归求,数列1, 2, 4, 2, 3, 6, 12, 6, 3 … 求第n项值

结果

1, 2, 4, 2, 3,
res:3
1, 2, 4, 2, 3, 6, 12, 6, 7, 14, 28,
res:28
1, 2, 4, 2, 3, 6, 12, 6, 7, 14, 28, 14, 15, 30, 60, 30, 31, 62, 124, 62, 63, 126, 252, 126, 127, 254, 508, 254, 255, 510, 1020, 510, 511, 1022, 2044, 1022, 1023, 2046, 4092, 2046, 2047, 4094, 8188, 4094, 4095, 8190, 16380, 8190, 8191, 16382, 32764, 16382, 16383, 32766, 65532, 32766, 32767,
res:32767
1, 2, 4, 2, 3, 6, 12, 6, 7, 14, 28, 14, 15, 30,
res:30
1, 2, 4, 2, 3, 6, 12, 6, 7, 14, 28, 14, 15, 30, 60, 30, 31, 62, 124, 62, 63,
res:63

代码

int _GetNextStartValue(int start_value, int count, int n, int& cur_index) {
	for (int i = 0; i < count; ++i, ++cur_index) {
		std::cout << start_value << ", ";
		if (cur_index == n) {
			return start_value;
		}
		
		start_value *= 2;
	}
	for (int i = 0; i < count-1; ++i, ++cur_index) {
		std::cout << start_value << ", ";
		if (cur_index == n) {
			return start_value;
		}
		start_value /= 2;
	}
	std::cout << start_value << ", ";
	if (cur_index == n)
		return start_value;
	++cur_index;
	return _GetNextStartValue(start_value + 1, count, n, cur_index);

}

int GetNValue(int n) {
	// 1, 2, 4, 2, 3, 6, 12, 6, 3 .... 求第n项值
	int cur_index = 0;
	return _GetNextStartValue(1, 2, n, cur_index);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值