Find factors of number using C++

In this article we will make program to find factors of a number using C++ language. Factors of a number are those numbers by which the number is perfectly divisible.

Consider a number 30. Now, the factors of 30 will be,

1,  2,  3,  5,  6,  10,  15 and 30 itself. All the prime numbers have only two factors i. e.  1  and the number itself. Now, let’s move to our program to find all the factors of number.

C++ program to find factors of number

We will take the number of which we have to find the factors from the user. Then we will find all the factors of given number using a for loop. You can use other loop for this purpose. Then we check that for which value less than that number, the number is perfectly divisible and print that value. Let’s see the program.

// C++ program to find all the factors of number

#include <iostream>
using namespace std;

int main(){
    int c, x;

    cout <<"Enter the number here to find factors : ";
    cin >>x;

    cout <<"\nAll the factors of " << x << " are ... \n";

    for(c = 1; c <= x; ++c){
        if(x%c == 0){
            cout <<c <<"  ";
        }
    }

    return 0;
}

Output of find factors program

find-factors-of-number-in-c

If we give any prime number as input then we will get only two factors which will be 1 and that number. Suppose, a user gives 23 as input. Then the program will print the factors are 1 and 23.

Enter the number here to find factors : 23

All the factors of 23 are ...
1  23

Previous pageLeap year program

Next pageSum of natural numbers