
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
Editorial
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. |
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