2025 牛客暑期多校训练营 7——Ivory(数学递推与gcd结合) · znzryb
## 思路讲解

## AC代码
[https://ac.nowcoder.com/acm/contest/view-submission?submissionId=78683868](https://ac.nowcoder.com/acm/contest/view-submission?submissionId=78683868)
::: 源代码
```cpp
// by Gospel_rock
#include <bits/stdc++.h>
#include <functional>
#define all(vec) vec.begin(),vec.end()
#define pb push_back
#define EB emplace_back
#define EM emplace
#define FI first
#define SE second
#define pct __builtin_popcountll
#define ctz __builtin_ctzll
#define SZ(a) ((long long) a.size())
#define FOR(i, a, b) for (long long i = (a); i <= (b); ++i)
#define ROF(i, a, b) for (long long i = (a); i >= (b); --i)
#define debug(var) cerr << #var <<":"<<var<<"\n";
#define cend cerr<<"\n-----------\n"
#define lson(var) (var<<1)
#define rson(var) ((var<<1)+1)
#define fsp(x) fixed<<setprecision(x)
using namespace std;
using ll = long long;using ull = unsigned long long;
using DB=double;using LD=long double;
using i128 = __int128;
using pdd = pair<DB,DB>;using plb = pair<ll,bool>;
using pll = pair<ll,ll>;using vll=vector<ll>;using vb=vector<bool>;
using tll = tuple<ll,ll,ll>;
using vpll = vector<pll>;using vtll = vector<tll>;
using vdb = vector<DB>;using vc=vector<char>;
using arr3 = array<ll,3> ;using arr2 = array<ll,2>;
static constexpr ll MAXN=(ll)1e6+10,INF=(ll)1e17+9; // 1e18+9也是素数
static constexpr ll mod=998244353;
static constexpr double eps=1e-8;const double pi=acos(-1.0);
ll N,M,Q,X,K,T,lT;
inline void __();
signed main()
{
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
cin>>lT;
while(lT--)
__();
return 0;
}
/*
*/
ll binpow(ll a,ll k,const ll &p=mod){
ll res=1;
a%=p;
while(k>0){
if((k&1)==1) res=a*res%p;
a=a*a%p;
k>>=1;
}
return res;
}
inline void __(){
ll a,b,c,d;
cin>>a>>b>>c>>d;
if(b>=d){
swap(a,c);
swap(b,d);
}
i128 ans=1;
function<void(ll,ll,ll,ll)> dfs=[&](ll a,ll b,ll c,ll d){
if(d>=b){
}else{
swap(a,c);
swap(b,d);
}
if(b==0 || d==0 || a==1 || c==1){
return;
}
if(b<=1 && d<=1){
if(b==0) a=1;
if(d==0) c=1;
ans*=__gcd(c,a);
ans%=mod;
return;
}
ll e=__gcd(a,c);
ans*=binpow(e, b);
ans%=mod;
ll x=a/e;
// dfs(e*x,b,e,b-d);
dfs(x,b,e,d-b);
};
dfs(a,b,c,d);
cout<<(ll)ans<<"\n";
}
/*
1
4 2 8 1
MLE
https://ac.nowcoder.com/acm/contest/view-submission?submissionId=78683716
TLE
https://ac.nowcoder.com/acm/contest/view-submission?submissionId=78683747
*/
```
:::
## 心路历程(WA,TLE,MLE……)
这个循环退出条件特别容易忘记。
```cpp
function<void(ll,ll,ll,ll)> dfs=[&](ll a,ll b,ll c,ll d){
if(d>=b){
}else{
swap(a,c);
swap(b,d);
}
if(b==0 || d==0 || a==1 || c==1){
return;
}
if(b<=1 && d<=1){
if(b==0) a=1;
if(d==0) c=1;
ans*=__gcd(c,a);
ans%=mod;
return;
}
ll e=__gcd(a,c);
ans*=binpow(e, b);
ans%=mod;
ll x=a/e;
// dfs(e*x,b,e,b-d);
dfs(x,b,e,d-b);
};
```