Блог пользователя AmirHoseinEsmailie

Автор AmirHoseinEsmailie, история, 2 дня назад, По-английски

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 .

  • Проголосовать: нравится
  • -30
  • Проголосовать: не нравится

»
2 дня назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

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

  • »
    »
    44 часа назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    yes. i'm agree with you