Divisor Counts

Pretty straight-forward problem. I struggled to allocate the memory at first (embarrassing), only to be reminded that I need to either globally allocate my non-const array or tag it with static. Silly mistakes. The solution is basically the Sieve of Eratosthenes except instead of a tagging numbers as composisite you increment a count of their divisors.

divisor_counts.cpp
divisor_counts.py

_23
#include <array>
_23
#include <iostream>
_23
_23
constexpr int kMaxSize = 3000001;
_23
_23
int main() {
_23
int n;
_23
std::cin >> n;
_23
std::ios_base::sync_with_stdio(false);
_23
std::cin.tie(NULL);
_23
static std::array<int, kMaxSize> divcount {};
_23
std::fill(divcount.begin()+2, divcount.end(), 2);
_23
std::cout << 1 << '\n';
_23
for (int i = 2; i <= n; ++i) {
_23
for (int j = 2; j <= n; ++j) {
_23
if (i*j > n) break;
_23
divcount[i*j]++;
_23
}
_23
std::cout << divcount[i] << '\n';
_23
}
_23
_23
return 0;
_23
}

If you found this solution helpful, consider leaving a star!