What is the sum of the digits of the number 2^1000?

前端 未结 10 1897
别跟我提以往
别跟我提以往 2021-01-02 03:13

This is a problem from Project Euler, and this question includes some source code, so consider this your spoiler alert, in case you are interested in solving it yourself. It

10条回答
  •  悲&欢浪女
    2021-01-02 03:37

    A solution without using the BigInteger class is to store each digit in it's own int and then do the multiplication manually.

    static void Problem16()
    {
        int[] digits = new int[350];
    
        //we're doing multiplication so start with a value of 1
        digits[0] = 1;
        //2^1000 so we'll be multiplying 1000 times
        for (int i = 0; i < 1000; i++)
        {
            //run down the entire array multiplying each digit by 2
            for (int j = digits.Length - 2; j >= 0; j--)
            {
                //multiply
                digits[j] *= 2;
                //carry
                digits[j + 1] += digits[j] / 10;
                //reduce
                digits[j] %= 10;
            }
        }
    
        //now just collect the result
        long result = 0;
        for (int i = 0; i < digits.Length; i++)
        {
            result += digits[i];
        }
    
        Console.WriteLine(result);
        Console.ReadKey();
    }
    

提交回复
热议问题