Finding all the factors of a natural number in C++
The factors of any number are whole numbers, which can divide the number
In this Answer, we will explore finding all the factors of any given natural number using C++. We will use the modulo operator (%) , also known as modulus or mod.
The modulo operator % and the factor of a number
The modulo operator calculates the remainder when dividing a number by another. Its syntax is as follows:
number1 % factor
The
number1will be the natural number being divided.The
factorwill be the number with which we are dividingnumber1.This line of code will give the remainder of this division.
Because a factor of a number will divide the number without leaving any remainder, it means the mod operator will return
Solution
Here is the solution to our problem. It takes a number as input and displays all the factors of that number, along with the total factors of that number.
#include <iostream>using namespace std;int main() {int number;cin >> number; // Taking the number as input.int count = 0; // count will store the number of factors of a number.for (int i=1; i < number+1 ; i++){if ((number%i) == 0){ //i will be the factor of number if it passes the condition.count++;cout << i << endl; // printing each factor}}cout << "The number " << number << " has " << count << " factors." << endl;}
Enter the input below
Explanation
Line 6: We take an integer as input from the user in the variable
number.Line 7: We initialize the variable
countas0. This stores the total number of factors of thenumber.Line 8: A
forloop checks each integer from1and goes up untilnumber+1.The reason for starting the loop from
1is that the remainder is always undefined for any division of. Its stopping condition is for
ito benumber+1, so the loop can also iterate wheniis thenumberitself.This is arbitrary in several ways. We can start from
2and go up till thenumbergiven that we have thecountinitialized asrather than to include and the number itself. However, the code on this line ensures that all factors are displayed without any extra line of code.
Lines 9–10: We specify an
ifcondition, which checks if there is no remainder when thenumberis divided byi. If this is the case, theniis a factor of thenumberand displayed to the user. Thecountis incremented because another factor is found.
Free Resources