Find the number of divisors of all numbers in the range [1, n]
Last Updated :
08 Jun, 2022
Given an integer N. The task is to find the number of divisors of all the numbers in the range [1, N].
Examples:
Input: N = 5
Output: 1 2 2 3 2
divisors(1) = 1
divisors(2) = 1 and 2
divisors(3) = 1 and 3
divisors(4) = 1, 2 and 4
divisors(5) = 1 and 5
Input: N = 10
Output: 1 2 2 3 2 4 2 4 3 4
Approach: Create an array arr[] of the size (N + 1) where arr[i] stores the number of divisors of i. Now for every j from the range [1, N], increment all the elements which are divisible by j.
For example, if j = 3 then update arr[3], arr[6], arr[9], …
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void findDivisors( int n)
{
int div [n + 1];
memset ( div , 0, sizeof div );
for ( int i = 1; i <= n; i++) {
for ( int j = 1; j * i <= n; j++)
div [i * j]++;
}
for ( int i = 1; i <= n; i++)
cout << div [i] << " " ;
}
int main()
{
int n = 10;
findDivisors(n);
return 0;
}
|
Java
class GFG
{
static void findDivisors( int n)
{
int [] div = new int [n + 1 ];
for ( int i = 1 ; i <= n; i++)
{
for ( int j = 1 ; j * i <= n; j++)
div[i * j]++;
}
for ( int i = 1 ; i <= n; i++)
System.out.print(div[i]+ " " );
}
public static void main(String args[])
{
int n = 10 ;
findDivisors(n);
}
}
|
Python3
def findDivisors(n):
div = [ 0 for i in range (n + 1 )]
for i in range ( 1 , n + 1 ):
for j in range ( 1 , n + 1 ):
if j * i < = n:
div[i * j] + = 1
for i in range ( 1 , n + 1 ):
print (div[i], end = " " )
if __name__ = = "__main__" :
n = 10
findDivisors(n)
|
C#
using System;
class GFG
{
static void findDivisors( int n)
{
int [] div = new int [n + 1];
for ( int i = 1; i <= n; i++)
{
for ( int j = 1; j * i <= n; j++)
div[i * j]++;
}
for ( int i = 1; i <= n; i++)
Console.Write(div[i]+ " " );
}
static void Main()
{
int n = 10;
findDivisors(n);
}
}
|
PHP
<?php
function findDivisors( $n )
{
$div = array_fill (0, $n + 2, 0);
for ( $i = 1; $i <= $n ; $i ++)
{
for ( $j = 1; $j * $i <= $n ; $j ++)
$div [ $i * $j ]++;
}
for ( $i = 1; $i <= $n ; $i ++)
echo $div [ $i ], " " ;
}
$n = 10;
findDivisors( $n );
?>
|
Javascript
<script>
function findDivisors(n)
{
let div = new Array(n + 1).fill(0);
for (let i = 1; i <= n; i++)
{
for (let j = 1; j * i <= n; j++)
div[i * j]++;
}
for (let i = 1; i <= n; i++)
document.write(div[i] + " " );
}
let n = 10;
findDivisors(n);
</script>
|
Output:
1 2 2 3 2 4 2 4 3 4
Time Complexity: O(n3/2)
Auxiliary Space: O(n)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...