#define PROBLEM "http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_1_A" #include <bits/stdc++.h> #include "../../Math/Number-Theory/eratosthenes-sieve.hpp" #include "../../Math/Number-Theory/osa_k.hpp" #include "../../Math/Number-Theory/prime-factorize.hpp" constexpr int N = 1e4; void test_osa_k() { const auto sieve = EratosthenesSieve(N); for (int i = 2; i <= N; ++i) { const auto expected = primeFactorize(i); const auto got = osa_k(i, sieve); assert(got == expected); } std::clog << __func__ << " : OK" << std::endl; } int main() { std::cout << "Hello World" << std::endl; test_osa_k(); return 0; }
#line 1 "test/helloworld/osa_k.test.cpp" #define PROBLEM "http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_1_A" #include <bits/stdc++.h> #line 5 "Math/Number-Theory/eratosthenes-sieve.hpp" /** * @brief Eratosthenes-Sieve (エラトステネスの篩) * @see https://qiita.com/rsk0315_h4x/items/ff3b542a4468679fb409 */ class EratosthenesSieve { private: int m_size; std::vector<int> m_minFactor; public: EratosthenesSieve() = default; //! [0, n] の範囲で篩を構築する explicit EratosthenesSieve(int n_) : m_size(n_ + 1) , m_minFactor(m_size) { std::iota(m_minFactor.begin(), m_minFactor.end(), 0); for (int i = 2; i * i < m_size; ++i) { if (m_minFactor[i] < i) continue; for (int j = i * i; j < m_size; j += i) { if (m_minFactor[j] == j) m_minFactor[j] = i; } } m_minFactor[0] = -1; if (n_ >= 1) m_minFactor[1] = -1; } bool isPrime(int x) const { assert(0 <= x && x < m_size); return m_minFactor[x] == x; } int minFactor(int x) const { assert(0 <= x && x < m_size); return m_minFactor[x]; } }; #line 2 "Math/Number-Theory/osa_k.hpp" #line 4 "Math/Number-Theory/osa_k.hpp" #line 6 "Math/Number-Theory/osa_k.hpp" /** * @brief osa_k() (前計算 $O(N \log \log N)$, 素因数分解 $O(\log N)$) * @see https://qiita.com/rsk0315_h4x/items/ff3b542a4468679fb409 */ std::map<int, int> osa_k(int n, const EratosthenesSieve& es) { std::map<int, int> ret; while (n > 1) { ++ret[es.minFactor(n)]; n /= es.minFactor(n); } return ret; } #line 3 "Math/Number-Theory/prime-factorize.hpp" /** * @brief primeFactorize() (素因数分解 $O(\sqrt n)$) */ template <class Integer> std::map<Integer, int> primeFactorize(Integer n) { std::map<Integer, int> res; for (Integer i = 2; i * i <= n; ++i) { while (n % i == 0) { ++res[i]; n /= i; } } if (n != 1) res[n] = 1; return res; } #line 7 "test/helloworld/osa_k.test.cpp" constexpr int N = 1e4; void test_osa_k() { const auto sieve = EratosthenesSieve(N); for (int i = 2; i <= N; ++i) { const auto expected = primeFactorize(i); const auto got = osa_k(i, sieve); assert(got == expected); } std::clog << __func__ << " : OK" << std::endl; } int main() { std::cout << "Hello World" << std::endl; test_osa_k(); return 0; }