题解 | 分元宵

分元宵

https://www.nowcoder.com/practice/0be3d626297a4c0aa99bf99d7cb888d5

Modern Cpp

读入a, b, c, d, p,结论就是计算pow(a * b, c * d)对p取模的结果,假设指数部分相乘不会爆__int128,使用快速幂配合龟速乘解决。

#include <iostream>
#include <string>
#include <algorithm>

using i64 = long long;
using i128 = __int128;

std::ostream& operator<<(std::ostream& os, i128 n) {
  if (n == 0) {
    return os << 0;
  }
  std::string s;
  while (n > 0) {
    s += char('0' + n % 10);
    n /= 10;
  }
  std::reverse(s.begin(), s.end());
  return os << s;
}

i128 toi128(const std::string& s) {
  i128 n = 0;
  for (auto c : s) {
    n = n * 10 + (c - '0');
  }
  return n;
}

int main() {
  std::ios::sync_with_stdio(false);
  std::cin.tie(nullptr);
  std::cout.tie(nullptr);

  std::string sa, sb, sc, sd, sp;
  std::cin >> sa >> sb >> sc >> sd >> sp;
  i128 a = toi128(sa), b = toi128(sb);
  i128 c = toi128(sc), d = toi128(sd);
  i128 p = toi128(sp);

  auto mul = [&](i128 x, i128 y){
    i128 res = 0;
    x %= p, y %= p;
    for(; y; x = (x + x) % p, y >>= 1){
      if(y & 1){
        res = (res + x) % p;
      }
    }
    return res;
  };

  auto power = [&](i128 x, i128 y){
    i128 res = 1 % p;
    for(; y; x = mul(x, x), y >>= 1){
      if(y & 1){
        res = mul(res, x);
      }
    }
    return res;
  };

  std::cout << power(mul(a, b), c * d) << "\n";

  return 0;
}

全部评论

相关推荐

03-17 23:54
黑龙江大学 Java
来个白菜也好啊qaq:可以的,大厂有的缺打手
点赞 评论 收藏
分享
03-31 00:39
门头沟学院 C++
牛客20485985...:抱抱😘,首先你还有春招,然后就算这时候没上岸也没关系,大部分人都是这样,毕业了再找也成,最后工作只是生活的一小部分,找到工作也不是一个必须的事情。不要气馁不要焦虑你只是陷入了短暂的低谷,你也一直有退路
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务