diff --git a/utilities/quotients.hpp b/utilities/quotients.hpp new file mode 100644 index 00000000..79af1519 --- /dev/null +++ b/utilities/quotients.hpp @@ -0,0 +1,26 @@ +#pragma once +#include +#include + +// Generate all quotients of n +// return: n/1, n/2, ..., n +// Complexity: O(sqrt(n)) +template std::vector get_quotients(T n) { + std::vector res; + for (T x = 1;; ++x) { + if (x * x >= n) { + const int sz = res.size(); + if (x * x == n) res.push_back(x); + res.reserve(res.size() + sz); + for (int i = sz - 1; i >= 0; --i) { + T tmp = n / res.at(i); + if (tmp < x) continue; + if (tmp == x and tmp * tmp == n) continue; + res.push_back(tmp); + } + return res; + } else { + res.push_back(x); + } + } +} diff --git a/utilities/quotients.md b/utilities/quotients.md new file mode 100644 index 00000000..ac6e7310 --- /dev/null +++ b/utilities/quotients.md @@ -0,0 +1,17 @@ +--- +title: Quotients of integer (商列挙) +documentation_of: ./quotients.hpp +--- + +正の整数 $n$ に対して $\lfloor n / k \rfloor$ ( $k$ は整数)の形で表される整数を昇順に列挙する.計算量は $O(\sqrt{n})$. + +## 使用方法 + +```cpp +long long n = 10; +vector v = get_quotients(n); // 1, 2, 3, 5, 10 +``` + +## 問題例 + +- [Library Checker: Enumerate Quotients](https://judge.yosupo.jp/problem/enumerate_quotients) diff --git a/utilities/test/quotients.test.cpp b/utilities/test/quotients.test.cpp new file mode 100644 index 00000000..f3f8d722 --- /dev/null +++ b/utilities/test/quotients.test.cpp @@ -0,0 +1,18 @@ +#define PROBLEM "https://judge.yosupo.jp/problem/enumerate_quotients" +#include "../quotients.hpp" + +#include +using namespace std; + +int main() { + cin.tie(nullptr); + ios::sync_with_stdio(false); + + long long N; + cin >> N; + + auto ret = get_quotients(N); + cout << ret.size() << '\n'; + for (auto x : ret) cout << x << ' '; + cout << '\n'; +}