Skip to content

Print all Divisors

Method-1

print_Divisor.cpp
#include <bits/stdc++.h>
using namespace std;

void print_Divisor(int n){
    cout << "All Divisors are: ";
    for(int i=1; i<=n; i++) {
        if(n%i == 0) {
            cout << i << " ";
        }
    }
    cout << endl;
}

int main() {
    int n;
    cin >> n;
    print_Divisor(n);
    return 0;
}

Input: 36
Output: All Divisors are: 1 2 3 4 6 9 12 18 36

Method-2

print_Divisor.cpp
#include <bits/stdc++.h>
using namespace std;

void print_Divisor(int n){
    cout << "All Divisors are: ";
    for(int i=1; i<=sqrt(n); i++) {
        if(n%i == 0) {
            cout << i << " ";
            if(i != n/i) {
                cout << n/i << " "; 
            }
        }
    }
    cout << endl;
}

int main() {
    int n;
    cin >> n;
    print_Divisor(n);
    return 0;
}

Input: 36
Output: All Divisors are: 1 2 3 4 6 9 12 18 36