Find all factors of a natural number | Set 1 - GeeksforGeeks

02 Mar, 2022
Given a natural number n, print all distinct divisors of it.
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.
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
Java
Python3
C#
PHP
Javascript
// C++ implementation of Naive method to print all// divisors#include <iostream>using namespace std; // function to print the divisorsvoid printDivisors(int n){    for (int i = 1; i <= n; i++)        if (n % i == 0)            cout <<" " << i;} /* Driver program to test above function */int main(){    cout <<"The divisors of 100 are: \n";    printDivisors(100);    return 0;} // this code is contributed by shivanisinghss2110
// C implementation of Naive method to print all// divisors#include<stdio.h> // function to print the divisorsvoid printDivisors(int n){    for (int i=1;i<=n;i++)        if (n%i==0)            printf("%d ",i);} /* Driver program to test above function */int main(){    printf("The divisors of 100 are: \n");    printDivisors(100);    return 0;}
// Java implementation of Naive method to print all// divisors class Test{    // method to print the divisors    static void printDivisors(int n)    {        for (int i=1;i<=n;i++)            if (n%i==0)                System.out.print(i+" ");    }     // Driver method    public static void main(String args[])    {        System.out.println("The divisors of 100 are: ");        printDivisors(100);;    }}
# Python implementation of Naive method# to print all divisors # method to print the divisorsdef printDivisors(n) :    i = 1    while i <= n :        if (n % i==0) :            print (i,end=" ")        i = i + 1         # Driver methodprint ("The divisors of 100 are: ")printDivisors(100) #This code is contributed by Nikita Tiwari.
// C# implementation of Naive method// to print all divisorsusing System; class GFG {         // method to print the divisors    static void printDivisors(int n)    {        for (int i = 1; i <= n; i++)            if (n % i == 0)                Console.Write( i + " ");    }     // Driver method    public static void Main()    {        Console.Write("The divisors of",                          " 100 are: ");        printDivisors(100);;    }} // This code is contributed by nitin mittal.
<?php// PHP implementation of Naive// method to print all divisors // function to print the divisorsfunction printDivisors($n){    for ($i = 1; $i <= $n; $i++)        if ($n % $i == 0)            echo $i," ";} // Driver Codeecho "The divisors of 100 are:\n";printDivisors(100); // This code is contributed by ajit?>
<script> // Javascript implementation of Naive method to print all// divisors // function to print the divisorsfunction printDivisors(n){    for (i=1;i<=n;i++)        if (n%i==0)            document.write(i+ " ");} /* Driver program to test above function */     document.write("The divisors of 100 are:" + "<br>");    printDivisors(100);     // This code is contributed by Mayank Tyagi     </script>
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++
C
Java
Python3
C#
PHP
Javascript
// A Better (than Naive) Solution to find all divisors#include <iostream>#include <math.h>using namespace std; // Function to print the divisorsvoid 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;             else // Otherwise print both                cout << " "<< i << " " << n/i;        }    }} /* Driver program to test above function */int main(){    cout <<"The divisors of 100 are: \n";    printDivisors(100);    return 0;} // this code is contributed by shivanisinghss2110
// A Better (than Naive) Solution to find all divisors#include <stdio.h>#include <math.h> // Function to print the divisorsvoid 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)                printf("%d ", i);             else // Otherwise print both                printf("%d %d ", i, n/i);        }    }} /* Driver program to test above function */int main(){    printf("The divisors of 100 are: \n");    printDivisors(100);    return 0;}
// A Better (than Naive) Solution to find all divisors class Test{    // method to print the divisors    static void printDivisors(int n)    {        // Note that this loop runs till square root        for (int i=1; i<=Math.sqrt(n); i++)        {            if (n%i==0)            {                // If divisors are equal, print only one                if (n/i == i)                    System.out.print(" "+ i);                      else // Otherwise print both                    System.out.print(i+" " + n/i + " " );            }        }    }     // Driver method    public static void main(String args[])    {        System.out.println("The divisors of 100 are: ");        printDivisors(100);;    }}
# A Better (than Naive) Solution to find all divisorsimport math # method to print the divisorsdef printDivisors(n) :         # Note that this loop runs till square root    i = 1    while i <= math.sqrt(n):                 if (n % i == 0) :                         # If divisors are equal, print only one            if (n / i == i) :                print (i,end=" ")            else :                # Otherwise print both                print (i , int(n/i), end=" ")        i = i + 1 # Driver methodprint ("The divisors of 100 are: ")printDivisors(100) #This code is contributed by Nikita Tiwari.
// A Better (than Naive) Solution to// find all divisorsusing System; class GFG {         // method to print the divisors    static void printDivisors(int n)    {                 // Note that this loop runs        // till square root        for (int i = 1; i <= Math.Sqrt(n);                                      i++)        {            if (n % i == 0)            {                                 // If divisors are equal,                // print only one                if (n / i == i)                    Console.Write(i + " ");                                 // Otherwise print both                else                    Console.Write(i + " "                            + n / i + " ");            }        }    }     // Driver method    public static void Main()    {        Console.Write("The divisors of "                          + "100 are: \n");        printDivisors(100);    }} // This code is contributed by Smitha
<?php// A Better (than Naive) Solution// to find all divisors // Function to print the divisorsfunction printDivisors($n){         // Note that this loop    // runs till square root    for ($i = 1; $i <= sqrt($n); $i++)    {        if ($n%$i == 0)        {                         // If divisors are equal,            // print only one            if ($n / $i == $i)                echo $i," ";             // Otherwise print both            else                echo $i," ", $n/$i," ";        }    }}     // Driver Code    echo "The divisors of 100 are: \n";    printDivisors(100);     // This code is contributed by anuj_67.  ?>
<script> // A Better (than Naive) Solution to find all divisors // Function to print the divisorsfunction printDivisors(n){         // Note that this loop runs till square root    for(let i = 1; i <= Math.sqrt(n); i++)    {        if (n % i == 0)        {                         // If divisors are equal, print only one            if (parseInt(n / i, 10) == i)                document.write(i);                             // Otherwise print both            else                document.write(i + " " +                      parseInt(n / i, 10) + " ");        }    }} // Driver codedocument.write("The divisors of 100 are: </br>");printDivisors(100); // This code is contributed by divyesh072019 </script>
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 2This article is contributed by Ashutosh Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
jit_t
vt_m
Smitha Dinesh Semwal
nitin mittal
kaiwalyakoparkar
mayanktyagi1709
vineetvdubey
divyesh072019
shivanisinghss2110
amartyaghoshgfg
simmytarika5
divisors
Numbers
prime-factor
sieve
Mathematical
Misc
Misc
Mathematical
Misc
Numbers
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find sum of elements in a given array
Program for factorial of a number
Top 10 algorithms in Interview Questions
vector::push_back() and vector::pop_back() in C++ STL
Overview of Data Structures | Set 1 (Linear Data Structures)
How to write Regular Expressions?
fgets() and gets() in C language