How to sum the digits of the number 2^N in Python

2 Answers

0 votes
def calculate_2_power_n_as_string(n):
    # Calculate 2^N as a string for large numbers
    result = ['1']  # List of characters for mutability

    for _ in range(n):
        carry = 0
        for i in range(len(result)):
            num = int(result[i]) * 2 + carry
            result[i] = str(num % 10)
            carry = num // 10
        while carry > 0:
            result.append(str(carry % 10))
            carry //= 10

    return ''.join(result)


def sum_of_digits(n):
    result = calculate_2_power_n_as_string(n)
    
    return sum(int(digit) for digit in result)


for n in [15, 100, 1000]:
    print(f"Sum of digits of 2^{n} is: {sum_of_digits(n)}")


  
'''
run:
  
Sum of digits of 2^15 is: 26
Sum of digits of 2^100 is: 115
Sum of digits of 2^1000 is: 1366

'''

 



answered Aug 1, 2025 by avibootz
0 votes
def sum_of_digits(power):
    # Calculate 2^N
    number = 2 ** power
    # Convert to string, iterate over digits, and sum them
    return sum(int(digit) for digit in str(number))


for n in [15, 100, 1000]:
    print(f"Sum of digits of 2^{n} is: {sum_of_digits(n)}")



  
'''
run:
  
Sum of digits of 2^15 is: 26
Sum of digits of 2^100 is: 115
Sum of digits of 2^1000 is: 1366

'''

 



answered Aug 1, 2025 by avibootz
...