VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cses-solutions-counting-divisors/

⇱ CSES Solutions - Counting Divisors - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solutions - Counting Divisors

Last Updated : 23 Jul, 2025

Given N integers as an array arr[], your task is to report for each integer the number of its divisors.

For example, if x=18, the correct answer is 6 because its divisors are 1,2,3,6,9,18.

Examples:

Input: N = 3, arr[] = {16, 17, 18}
Output:
5
2
6
Explanation:

  • There are 5 divisors of 16: 1, 2, 4, 8 and 16.
  • There are 2 divisors of 17: 1 and 17.
  • There are 6 divisors of 18: 1, 2, 3, 6, 9 and 18.

Input: N = 3, arr[] = {5, 6, 7}
Output:
2
4
2
Explanation:

  • There are 2 divisors of 5: 1 and 5.
  • There are 4 divisors of 6: 1, 2, 3 and 6.
  • There are 2 divisors of 7: 1 and 7.

Approach: To solve the problem, follow the below idea:

The problem can be solved by Precomputing the number of divisors for each number up to 1,000,004. Then, uses a nested loop to iterate over each number and its multiples, incrementing a counter for each multiple. This results in an array where the value at each index is the number of divisors for that index.

Step-by-step algorithm:

  • Create an array numDivisors to store the number of divisors for each number up to 1000004.
  • Iterate through each number i from 1 to 1000004.
  • For each i, iterate through multiples of i from j = i to 1000004.
  • Increment numDivisors[j] by 1 for each multiple.

Below is the implementation of the algorithm:


Output
5
2
6

Time complexity: O(N * log(max(arr[i]))), where N is the count of numbers given as input array arr[].
Auxiliary Space: O(N)

Comment
Article Tags: