Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>1. Detecting the overflow</strong>:</p> <pre><code>x = a * b; if (a != 0 &amp;&amp; x / a != b) { // overflow handling } </code></pre> <p>Edit: Fixed division by <code>0</code> (thanks Mark!)</p> <p><strong>2. Computing the carry</strong> is quite involved. One approach is to split both operands into half-words, then apply <a href="https://en.wikipedia.org/wiki/Multiplication_algorithm#Long_multiplication" rel="nofollow noreferrer">long multiplication</a> to the half-words:</p> <pre><code>uint64_t hi(uint64_t x) { return x &gt;&gt; 32; } uint64_t lo(uint64_t x) { return ((1L &lt;&lt; 32) - 1) &amp; x; } void multiply(uint64_t a, uint64_t b) { // actually uint32_t would do, but the casting is annoying uint64_t s0, s1, s2, s3; uint64_t x = lo(a) * lo(b); s0 = lo(x); x = hi(a) * lo(b) + hi(x); s1 = lo(x); s2 = hi(x); x = s1 + lo(a) * hi(b); s1 = lo(x); x = s2 + hi(a) * hi(b) + hi(x); s2 = lo(x); s3 = hi(x); uint64_t result = s1 &lt;&lt; 32 | s0; uint64_t carry = s3 &lt;&lt; 32 | s2; } </code></pre> <p>To see that none of the partial sums themselves can overflow, we consider the worst case:</p> <pre><code> x = s2 + hi(a) * hi(b) + hi(x) </code></pre> <p>Let <code>B = 1 &lt;&lt; 32</code>. We then have</p> <pre><code> x &lt;= (B - 1) + (B - 1)(B - 1) + (B - 1) &lt;= B*B - 1 &lt; B*B </code></pre> <p>I believe this will work - at least it handles Sjlver's test case. Aside from that, it is untested (and might not even compile, as I don't have a C++ compiler at hand anymore).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload