cp-library

C++ Library for Competitive Programming

View the Project on GitHub emthrm/cp-library

:heavy_check_mark: 素因数分解 (prime factorization)
(include/emthrm/math/prime_factorization.hpp)

時間計算量

$O(\sqrt{N})$

仕様

名前 戻り値
template <typename T>
std::vector<std::pair<T, int>> prime_factorization(T n);
$n$ の素因数分解

参考文献

TODO

Submissons

https://onlinejudge.u-aizu.ac.jp/solutions/problem/NTL_1_A/review/4088167/emthrm/C++14

Required by

Verified with

Code

#ifndef EMTHRM_MATH_PRIME_FACTORIZATION_HPP_
#define EMTHRM_MATH_PRIME_FACTORIZATION_HPP_

#include <utility>
#include <vector>

namespace emthrm {

template <typename T>
std::vector<std::pair<T, int>> prime_factorization(T n) {
  std::vector<std::pair<T, int>> res;
  for (T i = 2; i * i <= n; ++i) {
    if (n % i == 0) [[unlikely]] {
      int exponent = 0;
      for (; n % i == 0; n /= i) {
        ++exponent;
      }
      res.emplace_back(i, exponent);
    }
  }
  if (n > 1) res.emplace_back(n, 1);
  return res;
}

}  // namespace emthrm

#endif  // EMTHRM_MATH_PRIME_FACTORIZATION_HPP_
#line 1 "include/emthrm/math/prime_factorization.hpp"



#include <utility>
#include <vector>

namespace emthrm {

template <typename T>
std::vector<std::pair<T, int>> prime_factorization(T n) {
  std::vector<std::pair<T, int>> res;
  for (T i = 2; i * i <= n; ++i) {
    if (n % i == 0) [[unlikely]] {
      int exponent = 0;
      for (; n % i == 0; n /= i) {
        ++exponent;
      }
      res.emplace_back(i, exponent);
    }
  }
  if (n > 1) res.emplace_back(n, 1);
  return res;
}

}  // namespace emthrm
Back to top page