#include #include #include #include #include #include #include using I=long long; using V=std::vector; static const I P=65537; static const int A[3][2]={{0,1},{1,0},{1,-1}}; static const int B[3][2]={{0,1},{1,0},{1,-1}}; static const int C[3][3]={{0,1,0},{1,1,-1},{1,0,0}}; static const int IA=2, OA=2; static I mod(I x){x%=P;return x<0?x+P:x;} struct Plan{I mul,add;bool split;}; static std::map,Plan> cache; static Plan plan(int n,int m,int d){ auto key=std::make_tuple(n,m,d);auto it=cache.find(key); if(it!=cache.end())return it->second; Plan r{I(n)*m,I(n)*m-(n+m-1),false}; if(d>0 && std::min(n,m)>1){ int h=(std::max(n,m)+1)/2;auto q=plan(h,h,d-1); Plan c{3*q.mul,3*q.add+I(IA)*h+I(OA+2)*(2*h-1),true}; if(c.mul+c.add&a,const int*r){ V z(a[0].size());for(size_t i=0;i p; for(int t=0;t<3;++t)p[t]=mul(lin2(a0,a1,A[t]),lin2(b0,b1,B[t]),d-1); std::array c;for(int t=0;t<3;++t)c[t]=lin3(p,C[t]); V z(4*h-1);std::copy(c[0].begin(),c[0].end(),z.begin()); for(int t=1;t<3;++t)for(int j=0;j<2*h-1;++j)z[t*h+j]=mod(z[t*h+j]+c[t][j]); z.resize(n+m-1);return z; } extern "C" int sorilun_mul(const I*a,int n,const I*b,int m,int d,I*out){ try{ if(n<1||m<1||n>8192||m>8192||d<0||d>20)return 1; V av(a,a+n),bv(b,b+m);auto z=mul(av,bv,d);std::copy(z.begin(),z.end(),out);return 0; }catch(...){return 2;} } extern "C" void sorilun_clear_cache(){cache.clear();}