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 Combinatorics
  • MCQs on Combinatorics
  • Basics of Combinatorics
  • Permutation and Combination
  • Permutation Vs Combination
  • Binomial Coefficient
  • Calculate nPr
  • Calculate nCr
  • Pigeonhole Principle
  • Principle of Inclusion-Exclusion
  • Catalan Number
  • Lexicographic Rank
  • Next permutation
  • Previous Permutation
Open In App
Next Article:
Print all prime factors of a given number
Next article icon

Generating all divisors of a number using its prime factorization

Last Updated : 14 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an integer N, the task is to find all of its divisors using its prime factorization.

Examples: 

Input: N = 6 
Output: 1 2 3 6

Input: N = 10 
Output: 1 2 5 10

Approach: As every number greater than 1 can be represented in its prime factorization as p1a1*p2a2*......*pkak, where pi is a prime number, k ? 1 and ai is a positive integer. 
Now all the possible divisors can be generated recursively if the count of occurrence of every prime factor of n is known. For every prime factor pi, it can be included x times where 0 ? x ? ai. First, find the prime factorization of n using this approach and for every prime factor, store it with the count of its occurrence.

Below is the implementation of the above approach:

C++
// C++ implementation of the approach #include "iostream" #include "vector" using namespace std;  struct primeFactorization {      // to store the prime factor     // and its highest power     int countOfPf, primeFactor; };  // Recursive function to generate all the // divisors from the prime factors void generateDivisors(int curIndex, int curDivisor,                       vector<primeFactorization>& arr) {      // Base case i.e. we do not have more     // primeFactors to include     if (curIndex == arr.size()) {         cout << curDivisor << ' ';         return;     }      for (int i = 0; i <= arr[curIndex].countOfPf; ++i) {         generateDivisors(curIndex + 1, curDivisor, arr);         curDivisor *= arr[curIndex].primeFactor;     } }  // Function to find the divisors of n void findDivisors(int n) {      // To store the prime factors along     // with their highest power     vector<primeFactorization> arr;      // Finding prime factorization of n     for (int i = 2; i * i <= n; ++i) {         if (n % i == 0) {             int count = 0;             while (n % i == 0) {                 n /= i;                 count += 1;             }              // For every prime factor we are storing             // count of it's occurrenceand itself.             arr.push_back({ count, i });         }     }      // If n is prime     if (n > 1) {         arr.push_back({ 1, n });     }      int curIndex = 0, curDivisor = 1;      // Generate all the divisors     generateDivisors(curIndex, curDivisor, arr); }  // Driver code int main() {     int n = 6;      findDivisors(n);      return 0; } 
Java
// Java implementation of the approach import java.util.*; class GFG  {  static class primeFactorization  {      // to store the prime factor     // and its highest power     int countOfPf, primeFactor;      public primeFactorization(int countOfPf,                                int primeFactor)     {         this.countOfPf = countOfPf;         this.primeFactor = primeFactor;     } }  // Recursive function to generate all the // divisors from the prime factors static void generateDivisors(int curIndex, int curDivisor,                            Vector<primeFactorization> arr) {      // Base case i.e. we do not have more     // primeFactors to include     if (curIndex == arr.size())      {         System.out.print(curDivisor + " ");         return;     }      for (int i = 0; i <= arr.get(curIndex).countOfPf; ++i)     {         generateDivisors(curIndex + 1, curDivisor, arr);         curDivisor *= arr.get(curIndex).primeFactor;     } }  // Function to find the divisors of n static void findDivisors(int n) {      // To store the prime factors along     // with their highest power     Vector<primeFactorization> arr = new Vector<>();      // Finding prime factorization of n     for (int i = 2; i * i <= n; ++i)     {         if (n % i == 0)         {             int count = 0;             while (n % i == 0)              {                 n /= i;                 count += 1;             }              // For every prime factor we are storing             // count of it's occurrenceand itself.             arr.add(new primeFactorization(count, i ));         }     }      // If n is prime     if (n > 1)     {         arr.add(new primeFactorization( 1, n ));     }      int curIndex = 0, curDivisor = 1;      // Generate all the divisors     generateDivisors(curIndex, curDivisor, arr); }  // Driver code public static void main(String []args)  {     int n = 6;      findDivisors(n); } }  // This code is contributed by Rajput-Ji 
Python3
# Python3 implementation of the approach   # Recursive function to generate all the  # divisors from the prime factors  def generateDivisors(curIndex, curDivisor, arr):          # Base case i.e. we do not have more      # primeFactors to include      if (curIndex == len(arr)):         print(curDivisor, end = ' ')         return          for i in range(arr[curIndex][0] + 1):         generateDivisors(curIndex + 1, curDivisor, arr)          curDivisor *= arr[curIndex][1]      # Function to find the divisors of n  def findDivisors(n):          # To store the prime factors along      # with their highest power      arr = []          # Finding prime factorization of n      i = 2     while(i * i <= n):         if (n % i == 0):             count = 0             while (n % i == 0):                 n //= i                  count += 1                              # For every prime factor we are storing              # count of it's occurrenceand itself.              arr.append([count, i])           # If n is prime      if (n > 1):         arr.append([1, n])           curIndex = 0     curDivisor = 1          # Generate all the divisors      generateDivisors(curIndex, curDivisor, arr)   # Driver code  n = 6 findDivisors(n)   # This code is contributed by SHUBHAMSINGH10 
C#
// C# implementation of the approach using System;  using System.Collections.Generic;  class GFG  {  public class primeFactorization  {      // to store the prime factor     // and its highest power     public int countOfPf, primeFactor;      public primeFactorization(int countOfPf,                                int primeFactor)     {         this.countOfPf = countOfPf;         this.primeFactor = primeFactor;     } }  // Recursive function to generate all the // divisors from the prime factors static void generateDivisors(int curIndex, int curDivisor,                              List<primeFactorization> arr) {      // Base case i.e. we do not have more     // primeFactors to include     if (curIndex == arr.Count)      {         Console.Write(curDivisor + " ");         return;     }      for (int i = 0; i <= arr[curIndex].countOfPf; ++i)     {         generateDivisors(curIndex + 1, curDivisor, arr);         curDivisor *= arr[curIndex].primeFactor;     } }  // Function to find the divisors of n static void findDivisors(int n) {      // To store the prime factors along     // with their highest power     List<primeFactorization> arr = new List<primeFactorization>();      // Finding prime factorization of n     for (int i = 2; i * i <= n; ++i)     {         if (n % i == 0)         {             int count = 0;             while (n % i == 0)              {                 n /= i;                 count += 1;             }              // For every prime factor we are storing             // count of it's occurrenceand itself.             arr.Add(new primeFactorization(count, i ));         }     }      // If n is prime     if (n > 1)     {         arr.Add(new primeFactorization( 1, n ));     }      int curIndex = 0, curDivisor = 1;      // Generate all the divisors     generateDivisors(curIndex, curDivisor, arr); }  // Driver code public static void Main(String []args)  {     int n = 6;      findDivisors(n); } }  // This code is contributed by PrinciRaj1992 
JavaScript
<script> // Javascript implementation of the approach  // Recursive function to generate all the // divisors from the prime factors function generateDivisors(curIndex, curDivisor, arr) {      // Base case i.e. we do not have more     // primeFactors to include     if (curIndex == arr.length) {         document.write(curDivisor + " ");         return;     }      for (var i = 0; i <= arr[curIndex][0]; ++i) {         generateDivisors(curIndex + 1, curDivisor, arr);         curDivisor *= arr[curIndex][1];     } }  // Function to find the divisors of n function findDivisors(n) {      // To store the prime factors along     // with their highest power     arr = [];      // Finding prime factorization of n     for (var i = 2; i * i <= n; ++i) {         if (n % i == 0) {             var count = 0;             while (n % i == 0) {                 n /= i;                 count += 1;             }              // For every prime factor we are storing             // count of it's occurrenceand itself.             arr.push([ count, i ]);         }     }      // If n is prime     if (n > 1) {         arr.push([ 1, n ]);     }      var curIndex = 0, curDivisor = 1;      // Generate all the divisors     generateDivisors(curIndex, curDivisor, arr); }   // driver code var n = 6; findDivisors(n); // This code contributed by shubhamsingh10 </script> 

Output
1 3 2 6

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


Next Article
Print all prime factors of a given number

B

BhupendraYadav
Improve
Article Tags :
  • Combinatorial
  • Recursion
  • DSA
  • prime-factor
  • divisors
Practice Tags :
  • Combinatorial
  • Recursion

Similar Reads

  • Sum of Factors of a Number using Prime Factorization
    Given a number N. The task is to find the sum of all factors of the given number N. Examples: Input : N = 12 Output : 28 All factors of 12 are: 1,2,3,4,6,12 Input : 60 Output : 168 Approach: Suppose N = 1100, the idea is to first find the prime factorization of the given number N. Therefore, the pri
    13 min read
  • Product of divisors of a number from a given list of its prime factors
    Given an array arr[] representing a list of prime factors of a given number, the task is to find the product of divisors of that number. Note: Since the product can be, very large printed, the answer is mod 109 + 7. Examples: Input: arr[] = {2, 2, 3} Output: 1728 Explanation: Product of the given pr
    8 min read
  • Print all prime factors of a given number
    Given a number n, the task is to find all prime factors of n. Examples: Input: n = 24Output: 2 2 2 3Explanation: The prime factorization of 24 is 23×3. Input: n = 13195Output: 5 7 13 29Explanation: The prime factorization of 13195 is 5×7×13×29. Approach: Every composite number has at least one prime
    6 min read
  • Sum of all proper divisors of a natural number
    Given a natural number, calculate sum of all its proper divisors. A proper divisor of a natural number is the divisor that is strictly less than the number. For example, number 20 has 5 proper divisors: 1, 2, 4, 5, 10, and the divisor summation is: 1 + 2 + 4 + 5 + 10 = 22.Examples : Input : num = 10
    6 min read
  • Distinct Prime Factors of a given number N
    Given a number N, the task is to find the distinct Prime Factors of N. Examples: Input: N = 12Output: 2 3Explanation: The factors of 12 are 1, 2, 3, 4, 6, 12.Among these the distinct prime factors are 2 and 3. Input: N = 39Output: 3 13 Approach: The approach is to use a map to check whether a given
    7 min read
  • Find maximum power of a number that divides a factorial
    Given two numbers, fact and n, find the largest power of n that divides fact! (Factorial of fact). Examples:  Input : fact = 5, n = 2 Output : 3 Explanation: Value of 5! is 120. The largest power of 2 that divides 120 is 8 (or 23 Input : fact = 146, n = 15 Output : 35 The idea is based on Legendre’s
    12 min read
  • Mathematical Algorithms - Prime Factorization and Divisors
    In the Mathematical algorithm there are two fundamental mathematical algorithms that is prime factorization and finding divisors. Prime factorization is the process of breaking down a number into its prime factors, while finding divisors involves identifying all the numbers that can evenly divide th
    3 min read
  • Sum of all prime divisors of all the numbers in range L-R
    Given two integers L and R. The task is to find the sum of all prime factors of every number in the range[L-R]. Examples: Input: l = 5, r = 10 Output: 17 5 is prime, hence sum of factors = 0 6 has prime factors 2 and 3, hence sum = 5 7 is prime, hence sum = 0 8 has prime factor 2, hence sum = 2 9 ha
    14 min read
  • Sum of divisors of factorial of a number
    Given a number n, we need to calculate the sum of divisors of factorial of the number. Examples: Input : 4 Output : 60 Factorial of 4 is 24. Divisors of 24 are 1 2 3 4 6 8 12 24, sum of these is 60. Input : 6 Output : 2418 A Simple Solution is to first compute the factorial of the given number, then
    14 min read
  • Find numbers with K odd divisors in a given range
    Given two numbers a and b, and a number k which is odd. The task is to find all the numbers between a and b (both inclusive) having exactly k divisors.Examples: Input : a = 2, b = 49, k = 3 Output: 4 // Between 2 and 49 there are four numbers // with three divisors // 4 (Divisors 1, 2, 4), 9 (Diviso
    8 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