title: Calculating pow(a,b) mod n
body: <p>I want to calculate a<sup>b</sup> <em>mod</em> n for use in RSA decryption. My code (below) returns incorrect answers. What is wrong with it?</p>
  
  <pre><code>unsigned long int decrypt2(int a,int b,int n)
  {
      unsigned long int res = 1;
  
      for (int i = 0; i &lt; (b / 2); i++)
      {
          res *= ((a * a) % n);
          res %= n;
      }
  
      if (b % n == 1)
          res *=a;
  
      res %=n;
      return res;
  }
  </code></pre>