Efficient program to print the number of factors of n numbers

Given an array of integers. We are required to write a program to print the number of factors of every element of the given array.

Examples:

Input: 10 12 14 
Output: 4 6 4 
Explanation: There are 4 factors of 10 (1, 2, 
5, 10) and 6 of 12 and 4 of 14.

Input: 100 1000 10000
Output: 9 16 25 
Explanation: There are 9 factors of 100  and
16 of 1000 and 25 of 10000.



Simple Approach: A simple approach will be to run two nested loops. One for traversing the array and other for calculating all factors of elements of array.
Time Complexity: O( n * n)
Auxiliary Space: O( 1 )

Efficient Approach: We can optimize the above approach by optimizing the number of operations required to calculate the factors of a number. We can calculate the factors of a number n in sqrt(n) operations using this approach.
Time Complexity: O( n * sqrt(n))
Auxiliary Space: O( 1 )

Best Approach: If you go through number theory, you will find an efficient way to find the number of factors. If we take a number, say in this case 30, then the prime factors of 30 will be 2, 3, 5 with count of each of these being 1 time, so total number of factors of 30 will be (1+1)*(1+1)*(1+1) = 8.
Therefore, the general formula of total number of factors of a given number will be:

Factors = (1+a1) * (1+a2) * (1+a3) * … (1+an)

where a1, a2, a3 …. an are count of distinct prime factors of n.

Let’s take another example to make things more clear. Let the number be 100 this time,
So 100 will have 2, 2, 5, 5. So the count of distinct prime factors of 100 are 2, 2. Hence number of factors will be (2+1)*(2+1) = 9.

Now, the best way to find the prime factorization will be to store the sieve of prime factors initially. Create the sieve in a way that it stores the smallest primes factor that divides itself. We can modify the Sieve of Eratostheneses to do this. Then simply for every number find the count of prime factors and multiply it to find the number of total factors .

Below is the implementation of above approach.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to count number of factors
// of an array of integers
#include <bits/stdc++.h>
using namespace std;
  
const int MAX = 1000001;
  
// array to store prime factors
int factor[MAX] = { 0 };
  
// function to generate all prime factors
// of numbers from 1 to 10^6
void generatePrimeFactors()
{
    factor[1] = 1;
  
    // Initializes all the positions with their value.
    for (int i = 2; i < MAX; i++)
        factor[i] = i;
  
    // Initializes all multiples of 2 with 2
    for (int i = 4; i < MAX; i += 2)
        factor[i] = 2;
  
    // A modified version of Sieve of Eratosthenes to
    // store the smallest prime factor that divides
    // every number.
    for (int i = 3; i * i < MAX; i++) {
        // check if it has no prime factor.
        if (factor[i] == i) {
            // Initializes of j starting from i*i
            for (int j = i * i; j < MAX; j += i) {
                // if it has no prime factor before, then
                // stores the smallest prime divisor
                if (factor[j] == j)
                    factor[j] = i;
            }
        }
    }
}
  
// function to calculate number of factors
int calculateNoOFactors(int n)
{
    if (n == 1)
        return 1;
  
    int ans = 1;
  
    // stores the smallest prime number
    // that divides n
    int dup = factor[n];
  
    // stores the count of number of times
    // a prime number divides n.
    int c = 1;
  
    // reduces to the next number after prime
    // factorization of n
    int j = n / factor[n];
  
    // false when prime factorization is done
    while (j != 1) {
        // if the same prime number is dividing n,
        // then we increase the count
        if (factor[j] == dup)
            c += 1;
  
        /* if its a new prime factor that is factorizing n, 
           then we again set c=1 and change dup to the new 
           prime factor, and apply the formula explained 
           above. */
        else {
            dup = factor[j];
            ans = ans * (c + 1);
            c = 1;
        }
  
        // prime factorizes a number
        j = j / factor[j];
    }
  
    // for the last prime factor
    ans = ans * (c + 1);
  
    return ans;
}
  
// Driver program to test above function
int main()
{
    // generate prime factors of number
    // upto 10^6
    generatePrimeFactors();
  
    int a[] = { 10, 30, 100, 450, 987 };
  
    int q = sizeof(a) / sizeof(a[0]);
  
    for (int i = 0; i < q; i++)
        cout << calculateNoOFactors(a[i]) << " ";
  
    return 0;
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// JAVA Code For Efficient program to print
// the number of factors of n numbers
import java.util.*;
  
class GFG {
  
    static int MAX = 1000001;
    static int factor[];
  
    // function to generate all prime
    // factors of numbers from 1 to 10^6
    static void generatePrimeFactors()
    {
        factor[1] = 1;
  
        // Initializes all the positions with
        // their value.
        for (int i = 2; i < MAX; i++)
            factor[i] = i;
  
        // Initializes all multiples of 2 with 2
        for (int i = 4; i < MAX; i += 2)
            factor[i] = 2;
  
        // A modified version of Sieve of
        // Eratosthenes to store the
        // smallest prime factor that
        // divides every number.
        for (int i = 3; i * i < MAX; i++) {
            // check if it has no prime factor.
            if (factor[i] == i) {
                // Initializes of j starting from i*i
                for (int j = i * i; j < MAX; j += i) {
                    // if it has no prime factor
                    // before, then stores the
                    // smallest prime divisor
                    if (factor[j] == j)
                        factor[j] = i;
                }
            }
        }
    }
  
    // function to calculate number of factors
    static int calculateNoOFactors(int n)
    {
        if (n == 1)
            return 1;
  
        int ans = 1;
  
        // stores the smallest prime number
        // that divides n
        int dup = factor[n];
  
        // stores the count of number of times
        // a prime number divides n.
        int c = 1;
  
        // reduces to the next number after prime
        // factorization of n
        int j = n / factor[n];
  
        // false when prime factorization is done
        while (j != 1) {
            // if the same prime number is dividing n,
            // then we increase the count
            if (factor[j] == dup)
                c += 1;
  
            /* if its a new prime factor that is 
               factorizing n, then we again set c=1 
               and change dup to the new prime factor,
               and apply the formula explained 
               above. */
            else {
                dup = factor[j];
                ans = ans * (c + 1);
                c = 1;
            }
  
            // prime factorizes a number
            j = j / factor[j];
        }
  
        // for the last prime factor
        ans = ans * (c + 1);
  
        return ans;
    }
  
    /* Driver program to test above function */
    public static void main(String[] args)
    {
        // array to store prime factors
        factor = new int[MAX];
        factor[0] = 0;
  
        // generate prime factors of number
        // upto 10^6
        generatePrimeFactors();
  
        int a[] = { 10, 30, 100, 450, 987 };
  
        int q = a.length;
  
        for (int i = 0; i < q; i++)
            System.out.print(calculateNoOFactors(a[i]) + " ");
    }
}
  
// This code is contributed by Arnav Kr. Mandal.
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to count 
# number of factors
# of an array of integers
MAX = 1000001;
  
# array to store
# prime factors
factor = [0]*(MAX + 1);
  
# function to generate all 
# prime factors of numbers
# from 1 to 10^6
def generatePrimeFactors():
    factor[1] = 1;
  
    # Initializes all the 
    # positions with their value.
    for i in range(2,MAX):
        factor[i] = i;
  
    # Initializes all 
    # multiples of 2 with 2
    for i in range(4,MAX,2):
        factor[i] = 2;
  
    # A modified version of 
    # Sieve of Eratosthenes
    # to store the smallest 
    # prime factor that divides
    # every number.
    i = 3;
    while(i * i < MAX):
        # check if it has
        # no prime factor.
        if (factor[i] == i):
            # Initializes of j 
            # starting from i*i
            j = i * i;
            while(j < MAX): 
                # if it has no prime factor 
                # before, then stores the 
                # smallest prime divisor
                if (factor[j] == j):
                    factor[j] = i;
                j += i;
        i+=1;
  
# function to calculate
# number of factors
def calculateNoOFactors(n):
    if (n == 1):
        return 1;
    ans = 1;
  
    # stores the smallest 
    # prime number that
    # divides n
    dup = factor[n];
  
    # stores the count of 
    # number of times a 
    # prime number divides n.
    c = 1;
  
    # reduces to the next 
    # number after prime
    # factorization of n
    j = int(n / factor[n]);
  
    # false when prime 
    # factorization is done
    while (j > 1):
        # if the same prime 
        # number is dividing 
        # n, then we increase
        # the count
        if (factor[j] == dup):
            c += 1;
  
        # if its a new prime factor
        # that is factorizing n, 
        # then we again set c=1 and 
        # change dup to the new prime 
        # factor, and apply the formula 
        # explained above. 
        else:
            dup = factor[j];
            ans = ans * (c + 1);
            c = 1;
  
        # prime factorizes
        # a number
        j = int(j / factor[j]);
  
    # for the last
    # prime factor
    ans = ans * (c + 1);
  
    return ans;
# Driver Code
  
if __name__ == "__main__":
      
      
# generate prime factors
# of number upto 10^6
    generatePrimeFactors()
    a = [10, 30, 100, 450, 987]
    q = len(a)
    for i in range (0,q):
        print(calculateNoOFactors(a[i]),end=" ")
  
# This code is contributed 
# by mits.
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to count number of factors
// of an array of integers
using System;
  
class GFG {
  
    static int MAX = 1000001;
      
    // array to store prime factors
    static int[] factor;
  
    // function to generate all prime
    // factors of numbers from 1 to 10^6
    static void generatePrimeFactors()
    {
          
        factor[1] = 1;
  
        // Initializes all the positions
        // with their value.
        for (int i = 2; i < MAX; i++)
            factor[i] = i;
  
        // Initializes all multiples of
        // 2 with 2
        for (int i = 4; i < MAX; i += 2)
            factor[i] = 2;
  
        // A modified version of Sieve of
        // Eratosthenes to store the
        // smallest prime factor that
        // divides every number.
        for (int i = 3; i * i < MAX; i++)
        {
              
            // check if it has no prime
            // factor.
            if (factor[i] == i) 
            {
                  
                // Initializes of j 
                // starting from i*i
                for (int j = i * i; 
                          j < MAX; j += i)
                {
                      
                    // if it has no prime
                    // factor before, then
                    // stores the smallest
                    // prime divisor
                    if (factor[j] == j)
                        factor[j] = i;
                }
            }
        }
    }
  
    // function to calculate number of
    // factors
    static int calculateNoOFactors(int n)
    {
        if (n == 1)
            return 1;
  
        int ans = 1;
  
        // stores the smallest prime 
        // number that divides n
        int dup = factor[n];
  
        // stores the count of number
        // of times a prime number
        // divides n.
        int c = 1;
  
        // reduces to the next number
        // after prime factorization
        // of n
        int j = n / factor[n];
  
        // false when prime factorization
        // is done
        while (j != 1) {
              
            // if the same prime number 
            // is dividing n, then we 
            // increase the count
            if (factor[j] == dup)
                c += 1;
  
            /* if its a new prime factor
            that is factorizing n, then 
            we again set c=1 and change 
            dup to the new prime factor,
            and apply the formula explained 
            above. */
            else {
                dup = factor[j];
                ans = ans * (c + 1);
                c = 1;
            }
  
            // prime factorizes a number
            j = j / factor[j];
        }
  
        // for the last prime factor
        ans = ans * (c + 1);
  
        return ans;
    }
  
    /* Driver program to test above
    function */
    public static void Main()
    {
          
        // array to store prime factors
        factor = new int[MAX];
        factor[0] = 0;
  
        // generate prime factors of number
        // upto 10^6
        generatePrimeFactors();
  
        int[] a = { 10, 30, 100, 450, 987 };
  
        int q = a.Length;
  
        for (int i = 0; i < q; i++)
            Console.Write(
                   calculateNoOFactors(a[i])
                                     + " ");
    }
}
  
// This code is contributed by vt_m.
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// It works properly on
// 64-bit PHP Compiler
  
// PHP program to count 
// number of factors
// of an array of integers
$MAX = 1000001;
  
// array to store
// prime factors
$factor = array_fill(0, $MAX + 1, 0);
  
// function to generate all 
// prime factors of numbers
// from 1 to 10^6
function generatePrimeFactors()
{
    global $factor;
    global $MAX;
    $factor[1] = 1;
  
    // Initializes all the 
    // positions with their value.
    for ($i = 2; $i < $MAX; $i++)
        $factor[$i] = $i;
  
    // Initializes all 
    // multiples of 2 with 2
    for ($i = 4; $i < $MAX; $i += 2)
        $factor[$i] = 2;
  
    // A modified version of 
    // Sieve of Eratosthenes
    // to store the smallest 
    // prime factor that divides
    // every number.
    for ($i = 3; $i * $i < $MAX; $i++)
    {
        // check if it has
        // no prime factor.
        if ($factor[$i] == $i)
        {
            // Initializes of j 
            // starting from i*i
            for ($j = $i * $i
                 $j < $MAX; $j += $i
            {
                // if it has no prime factor 
                // before, then stores the 
                // smallest prime divisor
                if ($factor[$j] == $j)
                    $factor[$j] = $i;
            }
        }
    }
}
  
// function to calculate
// number of factors
function calculateNoOFactors($n)
{
    global $factor;
    if ($n == 1)
        return 1;
  
    $ans = 1;
  
    // stores the smallest 
    // prime number that
    // divides n
    $dup = $factor[$n];
  
    // stores the count of 
    // number of times a 
    // prime number divides n.
    $c = 1;
  
    // reduces to the next 
    // number after prime
    // factorization of n
    $j = (int)($n / $factor[$n]);
  
    // false when prime 
    // factorization is done
    while ($j != 1)
    {
        // if the same prime 
        // number is dividing 
        // n, then we increase
        // the count
        if ($factor[$j] == $dup)
            $c += 1;
  
        /* if its a new prime factor
           that is factorizing n, 
           then we again set c=1 and 
           change dup to the new prime 
           factor, and apply the formula  
           explained above. */
        else 
        {
            $dup = $factor[$j];
            $ans = $ans * ($c + 1);
            $c = 1;
        }
  
        // prime factorizes
        // a number
        $j = (int)($j / $factor[$j]);
    }
  
    // for the last
    // prime factor
    $ans = $ans * ($c + 1);
  
    return $ans;
}
  
// Driver Code
  
// generate prime factors
// of number upto 10^6
generatePrimeFactors();
$a = array(10, 30, 100, 450, 987);
$q = sizeof($a);
for ($i = 0; $i < $q; $i++)
    echo calculateNoOFactors($a[$i]) . " ";
  
// This code is contributed 
// by mits.
?>
chevron_right


Output:
4 8 9 18 8 

Time Complexity: O(n * log(max(number))), where n is total number of elements in the array and max(number) represents the maximum number in the array.
Auxiliary Space: O(n) for calculating the sieve.

This article is contributed by Raja Vikramaditya. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.




Improved By : vt_m, Mithun Kumar



Article Tags :