Bash Script to Find Factors of a Number
Use a Bash script with a loop from 1 to the number and check if
number % i == 0 to print all factors; for example: for ((i=1; i<=num; i++)); do if (( num % i == 0 )); then echo $i; fi; done.Examples
Input6
Output1
2
3
6
Input13
Output1
13
Input1
Output1
How to Think About It
To find factors of a number, think of checking every number from 1 up to that number. If dividing the number by this candidate leaves no remainder, it means the candidate is a factor. We print all such candidates.
Algorithm
1
Get the input number.2
Start a loop from 1 to the input number.3
For each number in the loop, check if it divides the input number evenly (remainder zero).4
If yes, print that number as a factor.5
End the loop after reaching the input number.Code
bash
#!/bin/bash read -p "Enter a number: " num for ((i=1; i<=num; i++)); do if (( num % i == 0 )); then echo $i fi done
Output
Enter a number: 6
1
2
3
6
Dry Run
Let's trace the number 6 through the code
1
Start loop with i=1
Check if 6 % 1 == 0 → yes, print 1
2
Next i=2
Check if 6 % 2 == 0 → yes, print 2
3
Next i=3
Check if 6 % 3 == 0 → yes, print 3
| i | 6 % i | Is factor? |
|---|---|---|
| 1 | 0 | Yes |
| 2 | 0 | Yes |
| 3 | 0 | Yes |
| 4 | 2 | No |
| 5 | 1 | No |
| 6 | 0 | Yes |
Why This Works
Step 1: Loop through numbers
The script loops from 1 to the input number to check every possible factor.
Step 2: Check divisibility
Using num % i == 0 checks if the remainder is zero, meaning i divides num exactly.
Step 3: Print factors
When a factor is found, it is printed immediately to show all factors one by one.
Alternative Approaches
Using while loop
bash
#!/bin/bash read -p "Enter a number: " num i=1 while [ $i -le $num ]; do if (( num % i == 0 )); then echo $i fi ((i++)) done
This uses a while loop instead of for; functionally similar but shows different loop style.
Optimized up to sqrt(num)
bash
#!/bin/bash read -p "Enter a number: " num for ((i=1; i*i<=num; i++)); do if (( num % i == 0 )); then echo $i if (( i != num / i )); then echo $((num / i)) fi fi done
This prints factors in pairs and only loops up to the square root, improving efficiency for large numbers.
Complexity: O(n) time, O(1) space
Time Complexity
The script checks every number from 1 to n, so it runs in linear time O(n).
Space Complexity
Uses constant extra space O(1) as it only stores counters and prints results immediately.
Which Approach is Fastest?
The optimized sqrt(n) approach reduces time to O(√n), which is faster for large numbers but slightly more complex.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Simple for loop | O(n) | O(1) | Small to medium numbers |
| While loop | O(n) | O(1) | Same as for loop, different style |
| Optimized sqrt loop | O(√n) | O(1) | Large numbers, better performance |
Use modulo
% operator to check if a number divides another without remainder.Forgetting to include the last number itself as a factor or using incorrect loop bounds.