题目
用递归求,数列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);
}