Simple (and slow) implementation of extended multiplication for tests
| 24 | |
| 25 | // Simple (and slow) implementation of extended multiplication for tests |
| 26 | constexpr Catch::Detail::ExtendedMultResult<std::uint64_t> |
| 27 | extendedMultNaive( std::uint64_t lhs, std::uint64_t rhs ) { |
| 28 | // This is a simple long multiplication, where we split lhs and rhs |
| 29 | // into two 32-bit "digits", so that we can do ops with carry in 64-bits. |
| 30 | // |
| 31 | // 32b 32b 32b 32b |
| 32 | // lhs L1 L2 |
| 33 | // * rhs R1 R2 |
| 34 | // ------------------------ |
| 35 | // | R2 * L2 | |
| 36 | // | R2 * L1 | |
| 37 | // | R1 * L2 | |
| 38 | // | R1 * L1 | |
| 39 | // ------------------------- |
| 40 | // | a | b | c | d | |
| 41 | |
| 42 | #define CarryBits( x ) ( (x) >> 32 ) |
| 43 | #define Digits( x ) ( (x) & 0xFF'FF'FF'FF ) |
| 44 | |
| 45 | auto r2l2 = Digits( rhs ) * Digits( lhs ); |
| 46 | auto r2l1 = Digits( rhs ) * CarryBits( lhs ); |
| 47 | auto r1l2 = CarryBits( rhs ) * Digits( lhs ); |
| 48 | auto r1l1 = CarryBits( rhs ) * CarryBits( lhs ); |
| 49 | |
| 50 | // Sum to columns first |
| 51 | auto d = Digits( r2l2 ); |
| 52 | auto c = CarryBits( r2l2 ) + Digits( r2l1 ) + Digits( r1l2 ); |
| 53 | auto b = CarryBits( r2l1 ) + CarryBits( r1l2 ) + Digits( r1l1 ); |
| 54 | auto a = CarryBits( r1l1 ); |
| 55 | |
| 56 | // Propagate carries between columns |
| 57 | c += CarryBits( d ); |
| 58 | b += CarryBits( c ); |
| 59 | a += CarryBits( b ); |
| 60 | |
| 61 | // Remove the used carries |
| 62 | c = Digits( c ); |
| 63 | b = Digits( b ); |
| 64 | a = Digits( a ); |
| 65 | |
| 66 | #undef CarryBits |
| 67 | #undef Digits |
| 68 | |
| 69 | return { |
| 70 | a << 32 | b, // upper 64 bits |
| 71 | c << 32 | d // lower 64 bits |
| 72 | }; |
| 73 | } |
| 74 | |
| 75 | |
| 76 | } // namespace |