Efficient program to print the number of factors of n numbers
Last Updated :
03 Oct, 2022
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 Eratosthenes 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.
C++
// 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 calculateNoOfFactors(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 << calculateNoOfFactors(a[i]) << " ";
return 0;
}
Java
// 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 calculateNoOfFactors(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.
Python3
# 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 calculateNoOfFactors(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.
C#
// 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 calculateNoOfFactors(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.
PHP
<?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 calculateNoOfFactors($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.
?>
JavaScript
<script>
// javascript Code For Efficient program to print
// the number of factors of n numbers
var MAX = 1000001;
var factor = [];
// function to generate all prime
// factors of numbers from 1 to 10^6
function generatePrimeFactors() {
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 calculateNoOfFactors(n)
{
if (n == 1)
return 1;
var ans = 1;
// stores the smallest prime number
// that divides n
var dup = factor[n];
// stores the count of number of times
// a prime number divides n.
var c = 1;
// reduces to the next number after prime
// factorization of n
var 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 */
// array to store prime factors
factor = Array(MAX).fill(0);
factor[0] = 0;
// generate prime factors of number
// upto 10^6
generatePrimeFactors();
var a = [ 10, 30, 100, 450, 987 ];
var q = a.length;
for (i = 0; i < q; i++)
document.write(calculateNoOFactors(a[i]) + " ");
// This code is contributed by aashish1995
</script>
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.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read