Display Factors of a Number

C++ Program to Display Factors of a Number (5 Methods)

BeginnerTopic: Array Operations Programs
Back

C++ Display Factors of a Number Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    int num;
    
    cout << "Enter a number: ";
    cin >> num;
    
    vector<int> factors;
    
    for (int i = 1; i <= num; i++) {
        if (num % i == 0) {
            factors.push_back(i);
        }
    }
    
    cout << "Factors of " << num << " are: ";
    for (int i = 0; i < factors.size(); i++) {
        cout << factors[i] << " ";
    }
    cout << endl;
    
    return 0;
}
Output
Enter a number: 24
Factors of 24 are: 1 2 3 4 6 8 12 24

Understanding Display Factors of a Number

This program demonstrates 5 different methods to find factors: checking all numbers, checking up to sqrt(n), using vectors, using arrays, and optimized approach.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Table of Contents