开发者

Multiplication of two deques of integers weird errors

this should be the final part of my integer cla开发者_StackOverflow社区ss, and it seems to be very easy, and yet, something is wrong. is this code correct for multiplication using 2 deques?

    // 0x12345 = {0x01, 0x23, 0x45}

    integer operator*(integer rhs){
        // long multiplication
        unsigned int zeros = 0;
        std::deque <uint8_t> row;
        std::deque <std::deque <uint8_t> > temp;
        integer out = 0;
        for(std::deque <uint8_t>::reverse_iterator i = value.rbegin(); i != value.rend(); i++){
            row = std::deque <uint8_t>(zeros++, 0); // zeros on the right hand side
            uint8_t carry = 0;
            for(std::deque <uint8_t>::reverse_iterator j = rhs.value.rbegin(); j != rhs.value.rend(); j++){
                uint16_t prod = (uint16_t(*i) * uint16_t(*j)) + carry;// multiply through
                row.push_front((uint8_t) prod);
                carry = prod >> 8;
            }
            if (carry != 0)
                row.push_front(carry);
            out += integer(row);
        }
        return out;
    }

it is giving me 4931550625 ^ 2 -> 24248133972899962689. assuming that the operator+ is correct, which i seems to be, is there some other explanation of why this is wrong

edit: i updated the code according to wxffles, but i think i did it wrong, since im still getting 2424..., and for 0x25 * 0x25 im getting 89 (decimal)

edit2: the correct code is posted


I think you are missing the last carry. Do you not need:

row.push_front(carry);

just before you add the row to out?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜