How to sum the digits of the number 2^N in C#

1 Answer

0 votes
using System;
using System.Text;

class PowerOfTwoDigitSum
{
    static string Calculate2PowerNAsString(int N) {
        // Calculate 2^N as a string for large numbers
        StringBuilder result = new StringBuilder("1");

        for (int i = 0; i < N; i++) {
            int carry = 0;
            for (int j = 0; j < result.Length; j++) {
                int digit = result[j] - '0';
                int num = digit * 2 + carry;
                result[j] = (char)((num % 10) + '0');
                carry = num / 10;
            }

            while (carry > 0) {
                result.Append((char)((carry % 10) + '0'));
                carry /= 10;
            }
        }

        return result.ToString();
    }

    static int SumOfDigits(int N) {
        string result = Calculate2PowerNAsString(N);
        int sum = 0;
        
        foreach (char digit in result) {
            sum += digit - '0';
        }
        
        return sum;
    }

    static void Main()
    {
        int N = 15;
        Console.WriteLine($"Sum of digits of 2^{N} is: {SumOfDigits(N)}");

        N = 100;
        Console.WriteLine($"Sum of digits of 2^{N} is: {SumOfDigits(N)}");

        N = 1000;
        Console.WriteLine($"Sum of digits of 2^{N} is: {SumOfDigits(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
edited Aug 1, 2025 by avibootz

Related questions

...