storing more than 2 power 31 on a 32-bit system

前端 未结 6 814
别那么骄傲
别那么骄傲 2020-12-09 05:17

I have to write a program that can calculate the powers of 2 power 2010 and to find the sum of the digits. eg:

if `2 power 12 => gives 4096          


        
6条回答
  •  暖寄归人
    2020-12-09 05:46

    GMP is perhaps the best, fastest free multi-architecture library for this. It provides a solid foundation for such calculations, including not only addition, but parsing from strings, multiplication, division, scientific operations, etc.

    For literature on the algorithms themselves, I highly recommend The Art of Computer Programming, Volume 2: Seminumerical Algorithms by Donald Knuth. This book is considered by many to be the best single reference for the topic. This book explains from the ground up how such arithmetic can take place on a machine that can only do 32-bit arithmetic.

    If you want to implement this calculation from scratch without using any tools, the following code block requires requires only the following additional methods to be supplied:

    unsigned int divModByTen(unsigned int *num, unsigned int length);
    bool isZero(unsigned int *num, unsigned int length);
    

    divModByTen should divide replace num in memory with the value of num / 10, and return the remainder. The implementation will take some effort, unless a library is used. isZero just checks if the number is all zero's in memory. Once we have these, we can use the following code sample:

    unsigned int div10;
    int decimalDigitSum;
    
    unsigned int hugeNumber[64];
    memset(twoPow2010, 0, sizeof(twoPow2010));
    twoPow2010[63] = 0x4000000;
    // at this point, twoPow2010 is 2^2010 encoded in binary stored in memory
    
    decimalDigitSum = 0;
    while (!izZero(hugeNumber, 64)) {
        mod10 = divModByTen(&hugeNumber[0], 64);
        decimalDigitSum += mod10;
    }
    
    printf("Digit Sum:%d", decimalDigitSum);
    

提交回复
热议问题