Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Check if all Prime factors of number N are unique or not
Next article icon

C++ Program To Find All Factors of A Natural Number

Last Updated : 17 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given a natural number n, print all distinct divisors of it.

 all divisors of a natural number

Examples:

 Input : n = 10          Output: 1 2 5 10     Input:  n = 100   Output: 1 2 4 5 10 20 25 50 100     Input:  n = 125   Output: 1 5 25 125

Note that this problem is different from finding all prime factors.

Recommended Practice
Count Numbers in Range
Try It!

A Naive Solution would be to iterate all the numbers from 1 to n, checking if that number divides n and printing it. Below is a program for the same:

C++
// C++ implementation of Naive  // method to print all divisors #include <iostream> using namespace std;  // Function to print the divisors void printDivisors(int n) {     for (int i = 1; i <= n; i++)         if (n % i == 0)             cout <<" " << i; }  // Driver code int main() {     cout <<"The divisors of 100 are: ";     printDivisors(100);     return 0; }  // This code is contributed by shivanisinghss2110 

Output:

The divisors of 100 are:   1 2 4 5 10 20 25 50 100

Time Complexity : O(n) 
Auxiliary Space : O(1)

Can we improve the above solution? 
If we look carefully, all the divisors are present in pairs. For example if n = 100, then the various pairs of divisors are: (1,100), (2,50), (4,25), (5,20), (10,10)
Using this fact we could speed up our program significantly. 
We, however, have to be careful if there are two equal divisors as in the case of (10, 10). In such case, we'd print only one of them. 

Below is an implementation for the same:

C++
// A Better (than Naive) Solution  // to find all divisors #include <iostream> #include <math.h> using namespace std;  // Function to print the divisors void printDivisors(int n) {     // Note that this loop runs      // till square root     for (int i = 1; i <= sqrt(n); i++)     {         if (n % i == 0)         {             // If divisors are equal,              // print only one             if (n / i == i)                 cout <<" "<< i;              // Otherwise print both             else                  cout << " "<< i << " " << n / i;         }     } }  // Driver code int main() {     cout <<"The divisors of 100 are: ";     printDivisors(100);     return 0; }  // This code is contributed by shivanisinghss2110 

Output:

The divisors of 100 are:   1 100 2 50 4 25 5 20 10

Time Complexity: O(sqrt(n)) 
Auxiliary Space : O(1)

However there is still a minor problem in the solution, can you guess? 
Yes! the output is not in a sorted fashion which we had got using the brute-force technique. Please refer below for an O(sqrt(n)) time solution that prints divisors in sorted order.
Find all divisors of a natural number | Set 2


Next Article
Check if all Prime factors of number N are unique or not
author
kartik
Improve
Article Tags :
  • Mathematical
  • C++ Programs
  • C++
  • DSA
  • C++ Basic Programs
Practice Tags :
  • CPP
  • Mathematical

Similar Reads

  • C++ Program to Find Factorial of a Number Using Iteration
    Factorial of a number n is the product of all integers from 1 to n. In this article, we will learn how to find the factorial of a number using iteration in C++. Example Input: 5Output: Factorial of 5 is 120Factorial of Number Using Iteration in C++To find the factorial of a given number we can use l
    2 min read
  • C++ Program to find sum of even factors of a number
    Given a number n, the task is to find the even factor sum of a number. Examples: Input : 30 Output : 48 Even dividers sum 2 + 6 + 10 + 30 = 48 Input : 18 Output : 26 Even dividers sum 2 + 6 + 18 = 26 Let p1, p2, … pk be prime factors of n. Let a1, a2, .. ak be highest powers of p1, p2, .. pk respect
    3 min read
  • C++ Program to Find Factorial of a Large Number Using Recursion
    Given a large number N, task is to find the factorial of N using recursion. Factorial of a non-negative integer is the multiplication of all integers smaller than or equal to n. For example factorial of 6 is 6*5*4*3*2*1 which is 720. Examples: Input : N = 100Output : 93326215443944152681699238856266
    2 min read
  • C++ Program for GCD of more than two (or array) numbers
    The GCD of three or more numbers equals the product of the prime factors common to all the numbers, but it can also be calculated by repeatedly taking the GCDs of pairs of numbers. gcd(a, b, c) = gcd(a, gcd(b, c)) = gcd(gcd(a, b), c) = gcd(gcd(a, c), b) C/C++ Code // C++ program to find GCD of two o
    3 min read
  • Check if all Prime factors of number N are unique or not
    Given a number N. The task is to check whether the given number N has unique prime factors or not. If yes then print YES else print NO.Examples: Input: N = 30 Output: YES Explanation: N = 30 = 2*3*5 As all the prime factors of 30 are unique.Input: N = 100 Output: NO Explanation: N = 100 = 2*2*5*5 As
    8 min read
  • Number of distinct prime factors of first n natural numbers
    In this article, we study an optimized way to calculate the distinct prime factorization up to n natural number using O O(n*log n) time complexity with pre-computation allowed.Prerequisites: Sieve of Eratosthenes, Least prime factor of numbers till n. Key Concept: Our idea is to store the Smallest P
    9 min read
  • C++ Program to Find Factorial of a Number Using Dynamic Programming
    The Factorial of a number N can be defined as the product of numbers from 1 to the number N. More formally factorial of n can be defined by function, [Tex]f(n) = 1 \times 2 \times 3 \times... \ n[/Tex] In this article, we will learn how to find the factorial of a number using dynamic programming in
    2 min read
  • C++ Program for Common Divisors of Two Numbers
    Given two integer numbers, the task is to find the count of all common divisors of given numbers. Input : a = 12, b = 24 Output: 6 // all common divisors are 1, 2, 3, // 4, 6 and 12 Input : a = 3, b = 17 Output: 1 // all common divisors are 1 Input : a = 20, b = 36 Output: 3 // all common divisors a
    2 min read
  • Find all digits of given number N that are factors of N
    Given a number N, the task is to print the digits of N which divide N. Example: Input: N = 234Output: 2 3 Input: N = 555Output: 5 Approach: The idea is to iterate over all the digits of N and check whether that digit divides N or not. Follow the steps below to solve the problem: Initialize the varia
    4 min read
  • Maximize the product of four factors of a Number
    Given an integer N, the task is to find the maximum product of A, B, C, D such that below conditions satisfy: N%A ==0 && N%B ==0 && N%C ==0 && N%D ==0.Maximize the product A*B*C*D where N = A+B+C+D. If no solution exists, print '-1' (without quotes). Examples: Input: N = 8 Ou
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences