Cho dãy: 0, 0, 2, 1, 4, 2, 6, 3, 8... Tìm số hạng thứ N.
Phân tích
Dãy xen kẽ hai dãy con:
- Vị trí lẻ: 0, 2, 4, 6, 8... → công thức
N-1. - Vị trí chẵn: 0, 1, 2, 3... → bằng nửa của vị trí lẻ trước đó.
Đệ quy: f(N) = N%2==1 ? N-1 : f(N-1)/2.
Mã nguồn C++
#include <iostream>
using namespace std;
int findNTerm(int N) {
if (N % 2 == 0) return findNTerm(N-1) / 2;
else return N - 1;
}
int main() {
int N = 13;
cout << N << "th term of the series is " << findNTerm(N) << endl; // 12
return 0;
}
Đầu ra
13th term of the series is 12