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.
% and the factor of a numberThe modulo operator calculates the remainder when dividing a number by another. Its syntax is as follows:
number1 % factor
The number1 will be the natural number being divided.
The factor will be the number with which we are dividing number1.
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
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
Line 6: We take an integer as input from the user in the variable number.
Line 7: We initialize the variable count as 0. This stores the total number of factors of the number.
Line 8: A for loop checks each integer from 1 and goes up until number+1.
The reason for starting the loop from 1 is that the remainder is always undefined for any division of
Its stopping condition is for i to be number+1, so the loop can also iterate when i is the number itself.
This is arbitrary in several ways. We can start from 2 and go up till the number given that we have the count initialized as
Lines 9–10: We specify an if condition, which checks if there is no remainder when the number is divided by i. If this is the case, then i is a factor of the number and displayed to the user. The count is incremented because another factor is found.
Free Resources