ja / en
Overview

約数列挙

2024/07/29
1 min read

Purpose

Enumerates the divisors of a given natural number.

Time Complexity

O(n)O(\sqrt{n})

Usage

For example, calling divisor(12) returns vector<int>{1,2,3,4,6,12}. It is guaranteed to be in ascending order.

Implementation

vector<int> divisor(int n) {
vector<int> head, tail;
for (int i = 1; i * i <= n; i++) {
if (n % i == 0) {
head.push_back(i);
if (i * i != n)
tail.push_back(n / i);
}
}
head.insert(head.end(), tail.rbegin(), tail.rend());
return head;
}

Verify

//TODO