Cho x, n. Tìm mảng tần suất 0-9 xuất hiện trong các số x¹, x², ..., xⁿ. Ví dụ: x=15, n=3 → 15, 225, 3375 → tần suất: [0,1,2,2,0,3,0,1,0,0].
Thuật toán
- Khởi tạo mảng freq[10] = {0}
- Với i = 1 đến n: tính x^i, tách chữ số, tăng freq[chữ số]
- In mảng freq
Chương trình C++
#include <iostream>
#include <cmath>
using namespace std;
void digitCount(double val, long arr[]) {
while ((long)val > 0) {
long digit = (long)val % 10;
arr[(int)digit]++;
val = (long)val / 10;
}
}
void generateFreqArray(int x, int n) {
long freq_count[10] = {0};
for (int i = 1; i <= n; i++) {
double val = pow((double)x, (double)i);
digitCount(val, freq_count);
}
cout << "[";
for (int i = 0; i <= 9; i++)
cout << freq_count[i] << " ";
cout << "\b]";
}
int main() {
int x = 15, n = 3;
cout << "The frequency array is: ";
generateFreqArray(x, n);
}
Kết quả
The frequency array is: [0 1 2 2 0 3 0 1 0 0]
Lưu ý
- Sử dụng double cho pow() có thể mất độ chính xác với số lớn
- Cải tiến: dùng big integer hoặc nhân thủ công để tránh tràn số