Print all Divisors of a number

Easy
0/40
Average time to solve is 15m
profile
Contributed by
485 upvotes
Asked in companies
AmazonGoogle inc

Problem statement

Given an integer ‘N’, your task is to write a program that returns all the divisors of ‘N’ in ascending order.


For example:
'N' = 5.
The divisors of 5 are 1, 5.
Detailed explanation ( Input/output format, Notes, Images )
Input Format :
The input consists of a single line containing an integer, ‘N’.
Output Format :
The output should be a single line containing the divisors of ‘N’, separated by spaces, in ascending order.
Sample Input 1 :
10
Sample Output 1 :
1 2 5 10
Explanation of Sample Input 1:
The divisors of 10 are 1,2,5,10.
Sample Input 2 :
6
Sample Output 2 :
1 2 3 6
Explanation of Sample Input 2:
The divisors of 6 are 1, 2, 3, and 6.
Constraints :
1 <= 'N' <= 10^5 
Hint

What remainder signifies divisibility by a number.

Approaches (2)
Iterative Approach

Iterate through all the numbers from 1 to 'N', and check if that number divides ‘N’, and if it divides, print it.

Time Complexity

O(N), where ‘N’ is the given number.

 

We are traversing from 1 to ‘N’, So the space complexity is O(N).

Space Complexity

O(1).

 

We use constant extra space, So the space complexity is O(1).

Code Solution
(100% EXP penalty)
Print all Divisors of a number
Full screen
Console