A factor of a number is a positive integer that divides the number without leaving a remainder. Given a number n, the task is to find and print all its factors.
Example
For n = 10, the factors are 1, 2, 5, 10 because each of these numbers divides 10 exactly.

Note: Finding all factors is different from finding all prime factors.
Approach
The basic approach is to check every number from 1 to n. If a number divides n without a remainder, it is a factor and is printed.
- Start a loop from 1 to n.
- Check whether n % i == 0.
- Print i if the remainder is 0.
#include <stdio.h>
// Prints all factors of n
void printFactors(int n)
{
// Check every number from 1 to n
for (int i = 1; i <= n; i++) {
// If i divides n, it is a factor
if (n % i == 0)
printf("%d ", i);
}
}
int main()
{
int n = 100;
printf("The factors of %d are: ", n);
// Print all factors of n
printFactors(n);
return 0;
}
Output
The factors of 100 are: 1 2 4 5 10 20 25 50 100
Explanation
- The loop checks every integer from 1 to n.
- n % i == 0 verifies whether i divides n exactly.
- Every number satisfying the condition is printed as a factor.
Optimized Approach
Factors occur in pairs. For example, for 100, the factor pairs are (1, 100), (2, 50), (4, 25), (5, 20), and (10, 10). Therefore, we check numbers only up to √n and use the corresponding factor from each pair.
- Iterate from 1 to √n.
- Check whether i divides n.
- Print i when it is a factor.
- Print the corresponding factor n / i in reverse order.
- Avoid printing the same factor twice when i * i == n.
#include <stdio.h>
// Prints all factors of n in sorted order
void printFactors(int n)
{
int i;
// Find factors up to the square root of n
for (i = 1; i * i <= n; i++) {
if (n % i == 0)
printf("%d ", i);
}
// Print corresponding factors in reverse order
for (i = i - 1; i >= 1; i--) {
if (n % i == 0 && i != n / i)
printf("%d ", n / i);
}
}
int main()
{
int n = 100;
printf("The factors of %d are: ", n);
// Print all factors of n
printFactors(n);
return 0;
}
Output
The factors of 100 are: 1 2 4 5 10 20 25 50 100
Explanation
- The first loop checks divisors only up to √n and prints the smaller factor of each pair.
- The second loop prints the corresponding larger factors in reverse order.
- i != n / i prevents a perfect square factor from being printed twice.
Note: The factors obtained using the √n approach are not directly printed in sorted order. For a sorted output, refer to Find all divisors of a natural number | Set 2.