Efficiently Finding Divisors of a Number

Правка en1, от AmirHoseinEsmailie, 2025-03-22 13:03:19

Sometimes we need to find the divisors of a number. The first way that might come to mind is: make a reverse loop (FOR loop) and divide the number by (i) to calculate the divisors. This approach takes O(N) time.


vector<int> get_divisors_reverse(int x) { vector<int> divs; for (int i = x; i >= 1; --i) { if (x % i == 0) { divs.push_back(i); } } return divs; }

But there are faster ways to calculate divisors.

This is a function that we can use to calculate the divisors of a number. Its time complexity is O(sqrt(N)).


vector<int> get_divisors(int x) { vector<int> divs; for (int i = 1; i * i <= x; ++i) { if (x % i == 0) { divs.push_back(i); if (i * i != x) { divs.push_back(x / i); } } } sort(divs.begin(), divs.end()); // Sorting is optional, depending on the requirement. return divs; }

if you know fastest way share it or comment it .

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en1 Английский AmirHoseinEsmailie 2025-03-22 13:03:19 1105 Initial revision (published)