Find all divisors of a natural number - Set 2 in C++


In this tutorial, we are going to write a program that finds all the divisors of a natural number. It's a straightforward problem. Let's see the steps to solve it.

  • Initialize the number.

  • Write a loop that iterates from 1 to the square root of the given number.

    • Check whether the given number is divisible by the current number or not.

    • If the above condition satisfies, then print the current number and given_number/current_number.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void findDivisors(int n) {
   for (int i = 1; i <= sqrt(n); i++) {
      if (n % i == 0) {
         if (n / i == i) {
            cout << i << " ";
         }
         else {
            cout << i << " " << n / i << " ";
         }
      }
   }
   cout << endl;
}
int main() {
   findDivisors(65);
   return 0;
}

Output

If you run the execute the above program, then you will get the following result.

1 65 5 13

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

Updated on: 01-Feb-2021

455 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements