We want all numbers of the form x^i + y^j <= bound for i, j >= 0. Since x and y can be 1, we must avoid infinite loops. We can enumerate all possible powers of x and y up to bound, and collect all unique sums into a set res.
#include<vector>#include<unordered_set>usingnamespace std;
vector<int> powerfulIntegers(int x, int y, int bound) {
unordered_set<int> res;
for (int a =1; a < bound +1; a *= x) {
for (int b =1; a + b <= bound; b *= y) {
res.insert(a + b);
if (y ==1) break;
}
if (x ==1) break;
}
return vector<int>(res.begin(), res.end());
}
import java.util.*;
classSolution {
public List<Integer>powerfulIntegers(int x, int y, int bound) {
Set<Integer> res =new HashSet<>();
for (int a = 1; a < bound + 1; a *= x) {
for (int b = 1; a + b <= bound; b *= y) {
res.add(a + b);
if (y == 1) break;
}
if (x == 1) break;
}
returnnew ArrayList<>(res);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
funpowerfulIntegers(x: Int, y: Int, bound: Int): List<Int> {
val res = mutableSetOf<Int>()
var a = 1while (a < bound + 1) {
var b = 1while (a + b <= bound) {
res.add(a + b)
if (y ==1) break b *= y
}
if (x ==1) break a *= x
}
return res.toList()
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
defpowerfulIntegers(x: int, y: int, bound: int) -> list[int]:
res = set()
a =1while a < bound +1:
b =1while a + b <= bound:
res.add(a + b)
if y ==1:
break b *= y
if x ==1:
break a *= x
return list(res)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
use std::collections::HashSet;
fnpowerful_integers(x: i32, y: i32, bound: i32) -> Vec<i32> {
letmut res = HashSet::new();
letmut a =1;
while a < bound +1 {
letmut b =1;
while a + b <= bound {
res.insert(a + b);
if y ==1 { break; }
b *= y;
}
if x ==1 { break; }
a *= x;
}
res.into_iter().collect()
}
1
2
3
4
5
6
7
8
9
10
11
exportfunctionpowerfulIntegers(x: number, y: number, bound: number):number[] {
constres=newSet<number>();
for (leta=1; a<bound+1; a*=x) {
for (letb=1; a+b<=bound; b*=y) {
res.add(a+b);
if (y===1) break;
}
if (x===1) break;
}
return Array.from(res);
}