# Find factors of a number in C ++

Hello Learners, Today We are going to talk about finding factors in C++ and will see how to implement this task. It is very common for every beginner.

In mathematics, factors are those numbers that have been divisible of a particular number. For Example, 20 has 6 factors – 1,2,4,5,10,20 .Each factor is divisible by 20.

We make a program that shows the factors of a respective number. It takes a number as input and runs a while loop until the temporary variable reaches the given number. The user inputs a number and by following that we need to start our while loop until the variable reaches the respective number. At last, the variables are printed on the screen of which the number is divisible.

### Code

**Finding Factors using For loopÂ **

#include<iostream> using namespace std; void factor(int n) { int i; for(i=1; i <= n/2; i++) { if (n % i == 0) cout << i << " "; } } int main() { int num = 20; cout << "The factors of " << num << " are : "; factor(num); return 0; }

Below is the output result of the above code:

The factors of 20 are : 1 2 4 5 10

**Finding factors using While loop**

Below is the program where we are using while loop for doing this task:

#include<iostream> using namespace std; int main() { int n, i = 1; cout << "Enter the number : " << endl; cin >> n; cout << "The factors of " << n << " are : " << endl; while (i <= n/2) { if (not(n % i)) cout << i << " "; i++; } cout << endl; }

Output :

Enter the number : 20 The factors of 20 are : 1 2 4 5 10

## Leave a Reply