Find all divisors of a natural number - Set 1 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 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.

Example

Let's see the code.

 Live Demo

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

Output

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

1 5 13 65

Conclusion

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

Updated on: 01-Feb-2021

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements