C Program to Find Factors of a Number
for loop from 1 to the number and print all values that divide the number evenly using if (num % i == 0).Examples
How to Think About It
Algorithm
Code
#include <stdio.h> int main() { int num, i; printf("Enter a number: "); scanf("%d", &num); printf("Factors of %d are: ", num); for(i = 1; i <= num; i++) { if(num % i == 0) { printf("%d ", i); } } return 0; }
Dry Run
Let's trace the input 6 through the code to find its factors.
Input number
num = 6
Start loop from 1 to 6
i = 1 to 6
Check if 6 % i == 0
For i=1: 6 % 1 = 0 (print 1) For i=2: 6 % 2 = 0 (print 2) For i=3: 6 % 3 = 0 (print 3) For i=4: 6 % 4 = 2 (skip) For i=5: 6 % 5 = 1 (skip) For i=6: 6 % 6 = 0 (print 6)
| i | num % i | Print factor? |
|---|---|---|
| 1 | 0 | Yes (1) |
| 2 | 0 | Yes (2) |
| 3 | 0 | Yes (3) |
| 4 | 2 | No |
| 5 | 1 | No |
| 6 | 0 | Yes (6) |
Why This Works
Step 1: Loop through numbers
The program checks every number from 1 to the input number to find possible factors.
Step 2: Check divisibility
Using num % i == 0 tests if the number divides evenly with no remainder.
Step 3: Print factors
If the condition is true, the current number is a factor and gets printed.
Alternative Approaches
#include <stdio.h> int main() { int num, i; printf("Enter a number: "); scanf("%d", &num); printf("Factors of %d are: 1 ", num); for(i = 2; i <= num / 2; i++) { if(num % i == 0) { printf("%d ", i); } } if(num != 1) printf("%d", num); return 0; }
#include <stdio.h> #include <math.h> int main() { int num, i; printf("Enter a number: "); scanf("%d", &num); printf("Factors of %d are: ", num); int limit = (int)sqrt(num); for(i = 1; i <= limit; i++) { if(num % i == 0) { printf("%d ", i); if(i != num / i) printf("%d ", num / i); } } return 0; }
Complexity: O(n) time, O(1) space
Time Complexity
The program loops from 1 to the input number, so it runs in linear time O(n). Each iteration does a simple modulus check.
Space Complexity
The program uses a fixed amount of memory for variables and prints results directly, so space complexity is O(1).
Which Approach is Fastest?
Using the square root optimization reduces time to about O(√n), which is faster for large numbers compared to the simple O(n) loop.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Simple loop 1 to n | O(n) | O(1) | Small to medium numbers, easy to understand |
| Loop 1 to n/2 | O(n/2) ~ O(n) | O(1) | Slightly faster, still simple |
| Square root optimization | O(√n) | O(1) | Large numbers, better performance |
% to find factors.