-
Notifications
You must be signed in to change notification settings - Fork 22
/
XpowerY.java
91 lines (84 loc) · 2.82 KB
/
XpowerY.java
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
82
83
84
85
86
87
88
89
90
91
package com.company.amazon;
import java.util.*;
public class XpowerY {
private static Map<Integer, Integer> xPowerY = new HashMap<>();
public static void main(String[] args) {
List<Integer> resultList = new ArrayList<>();
for (int i = 2; i <= 10000; i++) {
if (canBeExpressedAsXPowerY(i)) {
resultList.add(i);
}
}
System.out.println(resultList);
}
public static boolean canBeExpressedAsXPowerY(int num) {
for (int i = 2; i <= Math.sqrt(num); i++) {
int p = i;
while (p <= num) {
p = p * i;
if (p == num) {
return true;
}
}
}
return false;
}
public static boolean canBeExpressedAsXPowerY1(int num) {
int temp = num;
Map<Integer, Integer> powerMap = new HashMap<>();
Boolean result = false;
for (int i = 2; i <= num; i++) {
int power = 0;
while (temp > 0) {
if (temp % i == 0) {
temp = temp / i;
if (temp == 1) {
temp = 0;
}
power++;
} else {
break;
}
}
if (power > 0)
powerMap.put(i, power);
if (temp == 0) {
if (powerMap.size() > 0 && hasSamePower(powerMap)) {
Map.Entry<Integer, Integer> entry = powerMap.entrySet().iterator().next();
if (entry.getValue() == 1) { // Power should not be only 1, if all power are same
result = false;
} else {
if (powerMap.size() == 1) {
if (Math.pow(entry.getKey(), entry.getValue()) == num) {
result = true;
// xPowerY.put(entry.getKey(), entry.getValue());
} else {
result = false;
}
} else {
// xPowerY.put(powerMap.key, entry.getValue());
result = true;
// return true;
}
}
} else {
result = false;
}
break;
}
}
return result;
}
public static boolean hasSamePower(Map<Integer, Integer> powerMap) {
Set<Integer> set = new HashSet<>();
Set<Integer> keys = powerMap.keySet();
for (Integer i : keys) {
set.add(powerMap.get(i));
}
if (set.size() == 1) {
return true;
} else {
return false;
}
}
}