Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 3a1aae7

Browse filesBrowse files
authored
Merge pull request dubesar#96 from rajnis09/master
Added fastest way to compute number of divisors of a number
2 parents 75ec542 + 35cdfa1 commit 3a1aae7
Copy full SHA for 3a1aae7

File tree

Expand file treeCollapse file tree

1 file changed

+65
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+65
-0
lines changed
+65Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
class ComputeNumberOfDivisors {
2+
3+
// Method to find prime numbers
4+
static void SieveOfEratosthenes(int n, boolean prime[]) {
5+
for (int p = 2; p * p <= n; p++) {
6+
if (prime[p] == true) {
7+
for (int i = p * 2; i <= n; i += p)
8+
prime[i] = false;
9+
}
10+
}
11+
}
12+
13+
// Method to count divisors
14+
static int countDivisors(int n) {
15+
if (n == 1) {
16+
return 1;
17+
}
18+
boolean prime[] = new boolean[n + 1];
19+
boolean primeSquare[] = new boolean[(n * n) + 1];
20+
int a[] = new int[n];
21+
22+
prime[1] = false;
23+
for (int i = 2; i <= n; i++) {
24+
prime[i] = true;
25+
}
26+
27+
SieveOfEratosthenes(n, prime);
28+
int j = 0;
29+
for (int p = 2; p <= n; p++) {
30+
if (prime[p]) {
31+
a[j] = p;
32+
primeSquare[p * p] = true;
33+
j++;
34+
}
35+
}
36+
int ans = 1;
37+
for (int i = 0;; i++) {
38+
if (n < a[i] * a[i] * a[i]) {
39+
break;
40+
}
41+
int cnt = 1;
42+
while (n % a[i] == 0) {
43+
n = n / a[i];
44+
cnt = cnt + 1;
45+
}
46+
ans = ans * cnt;
47+
}
48+
if (prime[n]) {
49+
ans = ans * 2;
50+
} else if (primeSquare[n]) {
51+
ans = ans * 3;
52+
} else if (n != 1) {
53+
ans = ans * 4;
54+
}
55+
56+
return ans;
57+
}
58+
59+
public static void main(String[] args) {
60+
int x = 100;
61+
System.out.println("Total number of divisors of " + x + " are " + countDivisors(x));
62+
}
63+
}
64+
65+
// Time Complexity : O( n ^ (1/3) )

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.