File tree Expand file tree Collapse file tree 1 file changed +65
-0
lines changed
Filter options
Expand file tree Collapse file tree 1 file changed +65
-0
lines changed
Original file line number Diff line number Diff line change
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) )
You can’t perform that action at this time.
0 commit comments