<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Egemen Yalın</title>
    <description>The latest articles on DEV Community by Egemen Yalın (@duiccni).</description>
    <link>https://dev.to/duiccni</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1417397%2Fc3c7a917-9144-466b-95ab-60b112a41df2.jpeg</url>
      <title>DEV Community: Egemen Yalın</title>
      <link>https://dev.to/duiccni</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/duiccni"/>
    <language>en</language>
    <item>
      <title>Calculate Module of negative values FASTER.</title>
      <dc:creator>Egemen Yalın</dc:creator>
      <pubDate>Wed, 10 Apr 2024 18:31:38 +0000</pubDate>
      <link>https://dev.to/duiccni/calculate-module-of-negative-values-faster-371b</link>
      <guid>https://dev.to/duiccni/calculate-module-of-negative-values-faster-371b</guid>
      <description>&lt;p&gt;Many of us have attempted to calculate the absolute value of negative numbers at some point then went to Stackoverflow and tried to find an answer and probably found this code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// C/C++
int module(int a, int b) {
    return ((a % b) + b) % b;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;HOWEVER it is doing two divisions (module same thing for x86-cpus)&lt;br&gt;
You probably know divisions is a terribly slow operation&lt;br&gt;
Exactly 7-15 times slower than addition operation in modern cpus&lt;/p&gt;

&lt;p&gt;BUT you can lower this division usage in your module calculation this way:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int module(int a, int b) {
    return (a % b) + (((a ^ b) &amp;gt;&amp;gt; 31) &amp;amp; a);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This way uses trick checks if a * b is negative but you won't gonna see any multiplication or '&amp;lt;' symbol:&lt;br&gt;
((a ^ b) &amp;gt;&amp;gt; 31) this part does the job (a ^ b) is calculating a * b s symbol and '&amp;gt;&amp;gt; 31' this making sign bit to copy 31 times into all bits.&lt;/p&gt;

</description>
      <category>cpp</category>
      <category>algorithms</category>
      <category>math</category>
    </item>
  </channel>
</rss>
