-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrimeFactors
More file actions
32 lines (31 loc) · 996 Bytes
/
Copy pathPrimeFactors
File metadata and controls
32 lines (31 loc) · 996 Bytes
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
//Print prime factors of a given number
// This approach will achieve O(log n) if the number is a composite one
// Otherwise it will achieve O(n)
public static void printPrimeFactors(int n) {
int c = 2;
while (n > 1) {
if (n % c == 0) {
System.out.print(c + " ");
n /= c;
}
else c++;
}
}
//Print prime factors of a given number
//Time Complexity: O(n^(1/2) log n)
//Since outer loop runs for sqrt(n) times and
// for every loop we are dividing n by i which gives us logarithmic time complexity.
public static void primeFactor(int n) {
while (n % 2 == 0) {
System.out.print(2 + " ");
n /= 2;
}
for (int i = 3; i < Math.sqrt(n); i += 2) {
while (n % i == 0) {
System.out.print(i + " ");
n /= i;
}
}
if (n > 2)
System.out.print(n);
}