-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathall-divisors-of-a-number.cpp
More file actions
81 lines (60 loc) · 1.52 KB
/
Copy pathall-divisors-of-a-number.cpp
File metadata and controls
81 lines (60 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include<bits/stdc++.h>
using namespace std;
/*
Below is an iterative function to print all the divisors of an input natural number
Time complexity: theta(n)
Space complexity: theta(1)
Auxiliary space: theta(1)
*/
void print_all_divisors_of_number_naive_and_sorted(int n)
{
cout<<"\nAll the divisors of this number are:\n";
for(int i=1 ; i<=(n/2) ; i++)
{
if(n%i==0)
cout<<i<<" ";
}
cout<<n<<"\n";
}
/*
Below is an iterative function to print all the divisors of an input natural number
Time complexity: theta( sq. root(n) )
Space complexity: theta(1)
Auxiliary space: theta(1)
*/
void print_all_divisors_of_number_optimized(int n)
{
for(int i=1;i*i<=n;i++)
{
if(n%i==0)
cout<<i<<" ";
if(i!=(n/i))
cout<<(n/i)<<" ";
}
}
/*
Below is an iterative function to print all the divisors of an input natural number
Time complexity: theta( sq. root(n) )
Space complexity: theta(1)
Auxiliary space: theta(1)
*/
void print_all_divisors_of_number_optimized_and_sorted(int n)
{
int i;
// print divisors from 1 to sq. root(n) (inclusive range)
for(i=1;i*i<=n;i++)
if(n%i==0)
cout<<i<<" ";
// print divisors from sq. root(n) to n (inclusive range)
for( ;i>=1;i--)
if(n%i==0 && i!=(n/i))
cout<<(n/i)<<" ";
}
int main()
{
int n;
cout<<"Enter a natural number: ";
cin>>n;
print_all_divisors_of_number_optimized_and_sorted(n);
return 0;
}