Factors of a Natural Number in C++
Factors of n in C++: every i from 1 to n where n % i == 0. 24 → 1 2 3 4 6 8 12 24.
BeginnerLoop ProgramsExample 13 of 14
factors-of-a-natural-number.cpp
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}
Output
Enter a number: 24 Factors of 24 are: 1 2 3 4 6 8 12 24
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, ….