Factors of a Natural Number

Program to find all factors of a number

C++Beginner
C++
#include <iostream>
using namespace std;

int main() {
    int num;
    
    cout << "Enter a number: ";
    cin >> num;
    
    cout << "Factors of " << num << " are: ";
    
    for (int i = 1; i <= num; i++) {
        if (num % i == 0) {
            cout << i << " ";
        }
    }
    cout << endl;
    
    return 0;
}

Output

Enter a number: 24
Factors of 24 are: 1 2 3 4 6 8 12 24

Factors of a Number in C++

This program finds all factors (divisors) of a given number. A factor is an integer that divides the number evenly without leaving a remainder. Finding factors is fundamental in number theory, prime factorization, and many mathematical and programming problems.

What are Factors?

Factors (also called divisors) of a number are all integers that divide it evenly.

Mathematical definition:

  • If a divides b evenly (b % a == 0), then a is a factor of b

Examples:

Factors of 24:

  • 1, 2, 3, 4, 6, 8, 12, 24
  • Verification: 24 ÷ 1 = 24, 24 ÷ 2 = 12, 24 ÷ 3 = 8, etc.

Factors of 12:

  • 1, 2, 3, 4, 6, 12

Factors of 7 (prime number):

  • 1, 7 (only two factors)

Properties:

  • Every number has at least two factors: 1 and itself
  • Prime numbers have exactly two factors
  • Factors always come in pairs (except perfect squares)

Algorithm

  1. Iterate through all numbers from 1 to num
  2. Check if each number divides num evenly using modulo operator
  3. If num % i == 0, then i is a factor
  4. Print all factors found

Summary

  • Factors are all integers that divide a number evenly
  • Algorithm: Check each number from 1 to n using modulo operator
  • If num % i == 0, then i is a factor
  • Print all factors found
  • Time complexity: O(n) - can be optimized to O(√n)

This program teaches:

  • Modulo operator for divisibility checking
  • Iteration through all possibilities
  • Finding divisors of a number
  • Basic number theory concepts

Understanding factors helps in:

  • Prime factorization
  • Finding GCD and LCM
  • Number theory problems
  • Many mathematical programming challenges