Let’s define a “sevenish” number to be one which is either a power of 7, or the sum of unique powers of 7.

By | April 25, 2024

The first few sevenish numbers are 17849, and so on. Create an algorithm to find the nth sevenish number.

JAVA



public class SevenishNumber {
    public static int getNthSevenishNumber(int n) {
        int result = 0;
        int powerOfSeven = 1;
        while (n > 0) {
            if ((n & 1) == 1) {
                result += powerOfSeven;
            }
            n >>= 1;
            powerOfSeven *= 7;
        }
        return result;
    }
    public static void main(String[] args) {
        int n = 5;
        System.out.println("The " + n + "th sevenish number is: " + getNthSevenishNumber(n)); // Output: 49
    }
}

JAVASCRIPT

function getNthSevenishNumber(n) {
    let result = 0;
    let powerOfSeven = 1;
    while (n > 0) {
        if (n & 1) {
            result += powerOfSeven;
        }
        n >>= 1;
        powerOfSeven *= 7;
    }
    return result;
}
const n = 5;
console.log(`The ${n}th sevenish number is: ${getNthSevenishNumber(n)}`); // Output: 49 PYTHON def get_nth_sevenish_number(n):
result = 0
power_of_seven = 1
while n > 0:
if n & 1:
result += power_of_seven
n >>= 1
power_of_seven *= 7
return result n = 5
print(f"The {n}th sevenish number is: {get_nth_sevenish_number(n)}") # Output: 49

Leave a Reply

Your email address will not be published. Required fields are marked *