![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
#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.
Advertisements