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

C++Server Side ProgrammingProgramming

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.

raja
Published on 01-Feb-2021 12:10:17
Advertisements