Giới thiệu
Cho số nguyên N. Tìm phần tử thứ N của dãy chỉ chứa chữ số 4 và 7: 4, 7, 44, 47, 74, 77, 444, 447, 474, 477, 744…
Ví dụ minh họa
Đầu vào
N = 4
Đầu ra
47
Giải thích
Dãy: 4, 7, 44, 47, 74, 77, ...
Phương pháp giải: Xây dựng dãy bằng quy luật
Phần tử đầu: 4, 7. Với i ≥ 3:
- i lẻ:
series[i] = series[i/2]*10 + 4 - i chẵn:
series[i] = series[(i/2)-1]*10 + 7
Chương trình minh họa
#include <iostream>
using namespace std;
int findNthSeriesElement(int N) {
int series[N+1];
series[1] = 4;
series[2] = 7;
for (int i = 3; i <= N; i++) {
if (i % 2 != 0)
series[i] = series[i/2]*10 + 4;
else
series[i] = series[(i/2)-1]*10 + 7;
}
return series[N];
}
int main() {
int N = 9;
cout << "The " << N << "th element of the array is " << findNthSeriesElement(N);
return 0;
}
Đầu ra
The 9th element of the array is 474