码迷,mamicode.com
首页 > 其他好文 > 详细

求解模线性方程

时间:2016-05-02 21:26:25      阅读:478      评论:0      收藏:0      [点我收藏+]

标签:

    推论1:方程ax=b(mod n)对于未知量x有解,当且仅当gcd(a,n) | b。
    推论2:方程ax=b(mod n)或者对模n有d个不同的解,其中d=gcd(a,n),或者无解。
    定理1:设d=gcd(a,n),假定对整数x和y满足d=ax+by(比如用扩展Euclid算法求出的一组解)。如果d | b,则方程ax=b(mod n)有一个解x0满足x0=x*(b/d) mod n 。特别的设e=x0+n,方程ax=b(mod n)的最小整数解x1=e mod (n/d),最大整数解x2=x1+(d-1)*(n/d)。
    定理2:假设方程ax=b(mod n)有解,且x0是方程的任意一个解,则该方程对模n恰有d个不同的解(d=gcd(a,n)),分别为:xi=x0+i*(n/d) mod n 。

 

求所有解的伪代码如下:

技术分享

题目:poj 2115

思路:求A+x*C== B(mod 2^k ) 是否有解

若其有解,则xC == B-A(mod 2^k) 也有解;

技术分享
 1 #include <iostream>
 2 #include <algorithm>
 3 #include <stdlib.h>
 4 #include <time.h>
 5 #include <cmath>
 6 #include <cstdio>
 7 #include <string>
 8 #include <cstring>
 9 #include <vector>
10 #include <queue>
11 #include <stack>
12 #include <set>
13 
14 #define c_false ios_base::sync_with_stdio(false); cin.tie(0)
15 #define INF 0x3f3f3f3f
16 #define INFL 0x3f3f3f3f3f3f3f3f
17 #define zero_(x,y) memset(x , y , sizeof(x))
18 #define zero(x) memset(x , 0 , sizeof(x))
19 #define MAX(x) memset(x , 0x3f ,sizeof(x))
20 #define swa(x,y) {LL s;s=x;x=y;y=s;}
21 using namespace std ;
22 typedef long long LL;
23 const int N = 1e5 + 7;
24 
25 LL ex_gcd(LL a, LL b, LL &x, LL &y) {
26     LL d;
27     if (b == 0) {
28         x = 1; y = 0;
29         return a;
30     } else {
31         d = ex_gcd(b, a%b, y, x);
32         y -= a/b*x;
33         return d;
34     }
35 }
36 
37 LL Linear(LL a, LL b, LL c){
38     LL d, e, x, y;
39     d = ex_gcd(a, c, x, y);
40     if(b%d){
41         return -1;
42     }
43     e = x * (b/d) % c +c;
44     return e % (c/d);
45 }
46 
47 int main(){
48     //freopen("in.txt","r",stdin);
49     //freopen("out.txt","w",stdout);
50     //ios_base::sync_with_stdio(false); cin.tie(0);
51     long long d,a,b,c,k;
52     while(scanf("%I64d %I64d %I64d %I64d",&a,&b,&c,&k),a||b||c||k){
53         d=Linear(c,b-a,1LL<<k);
54         if(d==-1)
55             puts("FOREVER");
56         else
57             printf("%I64d\n",d);
58     }
59     return 0;
60 }
View Code

 

求解模线性方程

标签:

原文地址:http://www.cnblogs.com/yoyo-sincerely/p/5452986.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!