# Queries to Print All the Divisors of n using C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

In the given problem, we are required to print all the divisors of a given integer n.

Input: 15
Output: 1 3 5 15
Explanation
Divisors of 15 are: 1,3, 5, 15

Input: 30
Output: 1 2 3 5 15 30

In the given problem, we can apply the approach used in the sieve of Eratosthenes for finding all the divisors of n.

## Approach to find The Solution

In the given approach, we will apply the concept in which the sieve of Eratosthenes is based and find the divisors of n.

## Example

#include <bits/stdc++.h>
#define MOD 1000000007

using namespace std;

vector<int> divisors; // our vector containing number with all of its divisors
void findsieve(int max) { // filling data in vector divisors till 10e5
for(int i = 1; i <= max; i++) {
for(int j = i; j <= max; j += i)
divisors[j].push_back(i);
}
}
void __print(int n){ // the function to print divisors
for(auto x : divisors[n])
cout << x << " ";
cout << "\n";
}

int main() {
findsieve(100000); // we hardcode the sieve and divisors till 10e5
int n = 6; // the given n
__print(n);
n = 30; // new n
__print(n);
return 0;
}

## Output

1 2 3 6
1 2 3 5 6 10 15 30

## Explanation of the above code

In this approach, we follow the same concept as the sieve of Eratosthenes. We find the divisors of every number till 105. When we are given q queries, we don’t need to find the divisors, so this drastically reduces our time complexity when asked q queries. Hence, our complexity becomes O(Q*N), where Q is the number of queries we tackle, and N is the number of divisors of n.

## Conclusion

In this article, we solve a problem: Queries to print all the divisors of n where we apply the principle of the sieve of Eratosthenes. We also learned the C++ program for this problem and the complete approach ( Normal) by which we solved this problem. We can write the same program in other languages such as C, java, python, and other languages. We hope you find this article helpful.