C++ program to find the factors of a number

Program to find Factors of a number

To find answer of a number we will use a loop in which we start dividing the number with 1 up to the number itself and the numbers which perfectly divides the number are the factors.

For Example: 21

Factors are: 1, 3, 7, 21

C++ program to find the factors of a number

Algorithm:-

  1. Take input number.
  2. Input is stored in an int type variable say num.
  3. use loop from 1 to n
  4. Initialize factor=1
  5. Run a loop from factor=1 to num
    1. if num%factor==0 (if num is divisible by factor)
      1. print factor
    2. increment factor , factor ++
C++ program to find the factors of a number

C++ Code:-

 //C++ Program
    //Factors of a number
    #include <iostream>
    using namespace std;
    //main Program
    int main()
    {
        int num;
        cout << "Enter a positive number: ";
        //user input
        cin >> num;
        cout << "Factors of " << num << " are: " << endl;  
        //finding and printing factors
        for(int i = 1; i <= num; i++)
        {
            if(num % i == 0)
                cout << i << "\t";
        }
        return 0;
    }

Output

Enter a positive number: 36
Factors of 36 are: 
1    2    3    4    6    9    12    18    36