AmirHoseinEsmailie's blog

By AmirHoseinEsmailie, history, 18 hours ago, In English

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 .

  • Vote: I like it
  • -30
  • Vote: I do not like it

»
18 hours ago, # |
  Vote: I like it 0 Vote: I do not like it

even though almost everyone know this , still good work buddy keep up , its helpful for beginners;

  • »
    »
    11 hours ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    yes. i'm agree with you