Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,641 questions

55,376 answers

573 users

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

...