fork download
  1. // C++ Program to implement
  2. // the above approach
  3. #include <bits/stdc++.h>
  4. #define ll long long int
  5. using namespace std;
  6.  
  7. // Function to find a^b modulo M
  8. ll modPower(ll a, ll b, ll M)
  9. {
  10. ll res = 1;
  11. while (b) {
  12. if (b & 1)
  13. res = res * a % M;
  14. a = a * a % M;
  15. b >>= 1;
  16. }
  17. return res;
  18. }
  19.  
  20. // Function to find the first and last
  21. // M digits from N^K
  22. void findFirstAndLastM(ll N, ll K, ll M)
  23. {
  24. // Calculate Last M digits
  25. ll lastM
  26. = modPower(N, K, (1LL) * pow(10, M));
  27.  
  28. // Calculate First M digits
  29. ll firstM;
  30.  
  31. double y = (double)K * log10(N * 1.0);
  32.  
  33. // Extract the number after decimal
  34. y = y - (ll)y;
  35.  
  36. // Find 10 ^ y
  37. double temp = pow(10.0, y);
  38.  
  39. // Move the Decimal Point M - 1 digits forward
  40. firstM = temp * (1LL) * pow(10, M - 1);
  41.  
  42. // Print the result
  43. cout << firstM << " ";
  44. string s = to_string(lastM);
  45. int t = M - s.size();
  46. while(t--)
  47. {
  48. cout<<0;
  49. }
  50. cout<<lastM<<endl;
  51.  
  52. }
  53.  
  54. // Driver Code
  55. int main()
  56. {
  57. ll N = 12, K = 12, M = 4;
  58. cin>>N>>K>>M;
  59.  
  60. findFirstAndLastM(N, K, M);
  61. return 0;
  62. }
  63.  
Success #stdin #stdout 0s 5596KB
stdin
Standard input is empty
stdout
8916 8256