SGU 140. Integer Sequences 线性同余,数论 难度:2
140. Integer Sequences
time limit per test: 0.25 sec.
memory limit per test: 4096 KB
A sequence A is called an integer sequence of length N if all its elements A1 A2 .. AN are non-negative integers less than 2 000 000 000. Consider two integer sequences of length N, A and X. The result of their multiplication (A*X) is an integer number R=A1*X1 + A2*X2 + .. + AN*XN. Your task is to solve the equation A*X=B (mod P), given the integer sequence A and the integer numbers B and P.
Input
The first line contains the integer numbers N (1<=N<=100) - the length of the integer sequences - P (1<=P<=10 000) and B (0<=B<=P-1). The second line contains the elements of the sequence A, separated by blanks: A1 A2 .. AN.
Output
You should print one line containing the word "YES" if there exists at least one integer sequence X which is a solution to the equation, or print "NO" otherwise. If the answer is "YES", the next line should contain N non-negative integers separated by blanks: X1 X2 .. XN.
Sample Input #1
2 7 4 7 3
Sample Output #1
YES 0 6
Sample Input #2
3 10 1 2 4 6
Sample Output #2
NO
线性同余方程,不断使前k个项余p得到最大公约数,同除去最大公约数,逆推即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | #include <cstdio> using namespace std; int extgcd( int a, int b, int & x, int & y){ if (a==0){ x=0;y=1; return b; } int t=extgcd(b%a,a,x,y); int temp=x; x=y-b/a*x; y=temp; return t; } int num[110],x[110],y[110]; int main(){ int cgcd,n,p,b; scanf ( "%d%d%d" ,&n,&p,&b); for ( int i=0;i<n;i++){ scanf ( "%d" ,num+i); num[i]%=p; } cgcd=num[0]; for ( int i=1;i<n;i++){ cgcd=extgcd(cgcd,num[i],x[i],y[i]); } cgcd=extgcd(cgcd,p,x[n],y[n]); if (b%cgcd!=0) puts ( "NO" ); else { puts ( "YES" ); b/=cgcd; y[0]=1; for ( int i=n-1;i>=0;i--){ while (x[i+1]<0)x[i+1]+=p; b*=x[i+1]; b%=p; while (y[i]<0)y[i]+=p; y[i]=y[i]*b%p; } for ( int i=0;i<n;i++){ printf ( "%d%c" ,y[i],i==n-1? '\n' : ' ' ); } } return 0; } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 现代计算机视觉入门之:什么是图片特征编码
· .NET 9 new features-C#13新的锁类型和语义
· Linux系统下SQL Server数据库镜像配置全流程详解
· 现代计算机视觉入门之:什么是视频
· 你所不知道的 C/C++ 宏知识
· 不到万不得已,千万不要去外包
· C# WebAPI 插件热插拔(持续更新中)
· 会议真的有必要吗?我们产品开发9年了,但从来没开过会
· 【译】我们最喜欢的2024年的 Visual Studio 新功能
· 如何打造一个高并发系统?