Double precision in C++ (or pow(2, 1000))

前端 未结 7 516
情书的邮戳
情书的邮戳 2021-01-14 19:38

I\'m working on Project Euler to brush up on my C++ coding skills in preparation for the programming challenge(s) we\'ll be having this next semester (since they don\'t let

相关标签:
7条回答
  • 2021-01-14 20:16

    If you just keep track of each digit in a char array, this is easy. Doubling a digit is trivial, and if the result is greater than 10 you just subtract 10 and add a carry to the next digit. Start with a value of 1, loop over the doubling function 1000 times, and you're done. You can predict the number of digits you'll need with ceil(1000*log(2)/log(10)), or just add them dynamically.

    Spoiler alert: it appears I have to show the code before anyone will believe me. This is a simple implementation of a bignum with two functions, Double and Display. I didn't make it a class in the interest of simplicity. The digits are stored in a little-endian format, with the least significant digit first.




    typedef std::vector<char> bignum;
    
    void Double(bignum & num)
    {
        int carry = 0;
        for (bignum::iterator p = num.begin();  p != num.end();  ++p)
        {
            *p *= 2;
            *p += carry;
            carry = (*p >= 10);
            *p -= carry * 10;
        }
        if (carry != 0)
            num.push_back(carry);
    }
    
    void Display(bignum & num)
    {
        for (bignum::reverse_iterator p = num.rbegin();  p != num.rend();  ++p)
            std::cout << static_cast<int>(*p);
    }
    
    int main(int argc, char* argv[])
    {
        bignum num;
        num.push_back(1);
        for (int i = 0;  i < 1000;  ++i)
            Double(num);
        Display(num);
        std::cout << std::endl;
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题