Factors of a Natural Number in C++
List all factors of a natural number in C++ by testing every divisor from 1 to n with %. Traces 24 and shows the faster square-root pairing trick for big numbers.
1#include <iostream>2using namespace std;34int main() {5 int num;67 cout << "Enter a number: ";8 cin >> num;910 cout << "Factors of " << num << " are: ";1112 for (int i = 1; i <= num; i++) {13 if (num % i == 0) {14 cout << i << " ";15 }16 }17 cout << endl;1819 return 0;20}
Sample Output
Factors of 24 are: 1 2 3 4 6 8 12 24
Every i that divides 24.
In this one
- What a factor (divisor) is
- How % == 0 tests divisibility
- Why every number has 1 and itself as factors
- How to speed up the search by stopping at √n
How it works
- 1
Read num (24).
- 2
Loop i from 1 to 24.
- 3
If 24 % i == 0, print i.
- 4
Output: 1 2 3 4 6 8 12 24.
Edge cases
Prime input
Enter 13.
Only 1 and 13 divide it, so the output has two values.
Zero
Enter 0.
The loop condition 1 <= 0 is false, so no factors print. Every number divides 0, so 0 has no useful factor list.
What's going on
A factor of n divides n with remainder 0. Factors of 24: 1 2 3 4 6 8 12 24.
cin >> num;
Sample 24.
for (int i = 1; i <= num; i++)
if (num % i == 0) cout << i << " ";
Walk 24: 1 yes, 2 yes, 3 yes, 4 yes, 5 no, 6 yes, … 24 yes.
Prime 7 prints 1 7. 1 prints 1. 0 is a mess (every i divides 0); this loop would run zero times or behave badly depending on i <= 0. Don't type 0.
You can stop at sqrt(num) and print i and num/i as a pair. This program checks every i through n. Fine for 24. Slow for 10^9.
Order is increasing because i goes 1, 2, 3, ….
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which is not a factor of 18?
Pick an answer to check it.
Question 2
How many factors does 16 have?
Pick an answer to check it.
Questions people ask
How do I count factors instead?
Add a counter that increases each time num % i == 0.
How can this be faster?
Loop i while i * i <= num and print both i and num / i when i divides num. Take care not to print the square root twice.
Are negative numbers allowed?
The loop does not run for negatives, so nothing prints. Use the absolute value if you need them.