Finding all the factors of a natural number in C++

The factors of any number are whole numbers, which can divide the number evenlyThe division will leave no remainder. 11 is, by default, a factor for all natural numbers because any number can be divided by 11 without any remainder. Factorization supports structural analysis in various fields, such as math, cryptography, and engineering.

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 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 00. We can use this information to get all the factors of a number.

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 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 00.

    • 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 22 rather than 00to include 11 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 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

Copyright ©2025 Educative, Inc. All rights reserved