List all divisors of a number
List every positive divisor of a positive integer in ascending order.
Course progress
Problem 72 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
number = 12
Expected output
1 2 3 4 6 12
What is happening?
The positive integers that divide 12 with no remainder are 1, 2, 3, 4, 6, and 12.
Solution strategy
Build the right mental model
Test each integer from 1 through the number and keep the values that leave a zero remainder.
Core concepts
loops · divisibility
Complexity
Time O(n), space O(d), where d is the number of divisors.
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for list-number-divisors
using System;
using System.Collections.Generic;
class Program
{
static List<int> Divisors(int number)
{
if (number <= 0) throw new ArgumentOutOfRangeException("number");
var result = new List<int>();
for (int divisor = 1; divisor <= number; divisor++)
if (number % divisor == 0) result.Add(divisor);
return result;
}
static void Main()
{
Console.WriteLine(string.Join(" ", Divisors(12)));
}
}Knowledge check
Questions students often ask
What is the main idea behind list all divisors of a number?
Test each integer from 1 through the number and keep the values that leave a zero remainder.
What is the time and space complexity of this solution?
Time O(n), space O(d), where d is the number of divisors.
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.