title: first and last k digits of number n^n
body: <p>i have written a c++ code for generating first and last k digits of a number as large as 10^9. (k&lt;=9).</p>
  
  <pre><code>cin&gt;&gt;n&gt;&gt;k;
      cout &lt;&lt; (unsigned long)floor(pow(10.0, modf(n*log10((double)n), &amp;dummy) + k - 1)) &lt;&lt; " ";  // code that prints the first k digits
      long long int ans = foo(n,k);  // function that prints the last k digits
      if(ans==0)
      {
       for(int i=0;i&lt;k;i++) cout &lt;&lt; "0";
      }
      else{
              stringstream ss;
              string s;
              ss&lt;&lt;ans;
              ss&gt;&gt;s;
              if(s.size()!=k)
              {
                   for(int i=0;i&lt;(k-s.size());i++)
            s="0"+s;
              }
              cout&lt;&lt;s;
     }
  </code></pre>
  
  <p>where function foo() is:</p>
  
  <pre><code>long long int foo(int n, int k)  // code of the function
  {
    long long int m=1;
    for(; k &gt; 0; k--) m*=10;
  
    long long int r=1, t=n % m;
    while(n)
    {
      if (n % 2)
        r = r * t % m;
      t = t * t % m;
      n &gt;&gt;= 1;
    }
  
     return r;
  }
  </code></pre>
  
  <p>this gives me output as:
  if given 9 and 3 as inputs, it gives first and last 3 digits of 9 to the power 9 (9^9) i.e. 387 and 489. But I m still missing out some test cases.
  Can anyone please help me finding out the test case for which my code wouldn't work ?</p>
  
  <p>1 ≤ n ≤ 109, 1 ≤ k ≤ 9
  the problem statement: <a href="http://www.codechef.com/problems/MARCHA4/" rel="nofollow">http://www.codechef.com/problems/MARCHA4/</a></p>