Tutorialspoint
Problem
Solution
Submissions

Divisors of a Given Number

Certification: Basic Level Accuracy: 66.67% Submissions: 3 Points: 15

Write a C++ program that prints all the divisors of a given positive integer in ascending order.

Example 1
  • Input: n = 12
  • Output: 1, 2, 3, 4, 6, 12
  • Explanation:
    • Step 1: Find all integers from 1 to sqrt(n) that divide n without a remainder.
    • Step 2: For each divisor i found in Step 1, n/i is also a divisor.
    • Step 3: The divisors of 12 are 1, 2, 3, 4, 6, and 12 since each divides 12 without a remainder.
    • Step 4: Return the list of divisors in ascending order.
Example 2
  • Input: n = 17
  • Output: 1, 17
  • Explanation:
    • Step 1: Find all integers from 1 to sqrt(n) that divide n without a remainder.
    • Step 2: For each divisor i found in Step 1, n/i is also a divisor.
    • Step 3: Since 17 is a prime number, its only divisors are 1 and itself (17).
    • Step 4: Return the list of divisors in ascending order.
Constraints
  • 1 ≤ n ≤ 10^9
  • Input is a positive integer
  • Time Complexity: O(sqrt(n))
  • Space Complexity: O(sqrt(n)) for storing the divisors
Control StructuresFunctions / MethodsIBMDropbox
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • A naive approach would be to check all numbers from 1 to n, but that's inefficient for large n
  • For every divisor d below or equal to sqrt(n), n/d is also a divisor
  • Collect divisors from both sides and sort them before printing
  • Handle perfect squares carefully to avoid duplicate divisors

Steps to solve by this approach:

 Step 1: Create a vector to store all divisors of the number.

 Step 2: Iterate from 1 to the square root of the number.
 Step 3: Check if the current number is a divisor (n % i == 0).
 Step 4: If it is a divisor, add both i and n/i to the vector (unless they're equal).
 Step 5: Sort the vector of divisors to get them in ascending order.
 Step 6: Return the sorted vector containing all divisors.

Submitted Code :