Let’s define a “sevenish” number to be one which is either a power of 7, or the sum of unique powers of 7. The first few sevenish numbers are 1, 7, 8, 49, and so on. Create an algorithm to find the nth sevenish number.
The sequence of sevenish numbers can be systematically constructed using powers of 7 and sums of unique powers. By iterating through combinations of powers of 7, we can populate a list of sevenish numbers in ascending order until the nth number is found. Each new “sevenish” number can be derived by adding existing sevenish numbers to the next power of 7.
publicclassSolution {
publicintnthSevenishNumber(int n) {
List<Integer> sevenishNumbers =new ArrayList<>();
int powerOf7 = 1;
while (sevenishNumbers.size() < n) {
// Create new numbers using the current power of 7 List<Integer> newNumbers =new ArrayList<>();
newNumbers.add(powerOf7);
// Add sums of the current power with all previous numbersfor (int num : sevenishNumbers) {
newNumbers.add(num + powerOf7);
}
// Extend the sevenish list sevenishNumbers.addAll(newNumbers);
// Update power of 7 powerOf7 *= 7;
}
return sevenishNumbers.get(n - 1);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution:
defnth_sevenish_number(self, n: int) -> int:
# Generate powers of 7 (ascending order) sevenish_numbers = []
power_of_7 =1while len(sevenish_numbers) < n:
# Add current power of 7 new_numbers = [power_of_7]
# Add sums of the current power with all previous numbersfor num in sevenish_numbers:
new_numbers.append(num + power_of_7)
# Extend sevenish list and keep track of the nth one sevenish_numbers.extend(new_numbers)
power_of_7 *=7# Move to the next power of 7return sevenish_numbers[n -1]
Each iteration doubles the number of sevenish numbers (since for each existing number, you add a new one by adding the current power of 7).
To reach at least n numbers, the total number of generated numbers is O(2^k), where k ≈ log₂(n). But since the list grows exponentially, the total work is O(2ⁿ) in the worst case.
🧺 Space complexity: O(2^n)
The list sevenishNumbers can grow up to O(2ⁿ) in size, as each new power of 7 generates numbers for all previous combinations.