EOJ 1056 線性同余方程
1
/*
2
EOJ 1056 線性同余方程
3
4
5
----問題描述:
6
7
形如ax≡b(mod m) 的方程,稱為線性同余方程。編寫程序求解線性同余方程(基于歐幾里德算法)。
8
9
10
----輸入:
11
12
測試包含多組測試數據.
13
每組測試數據只含一行,每行有三個整數a,b,m(0<a,b,m<1000000)
14
15
16
----輸出:
17
18
每組測試數據只輸出一行.如果有解,則按解的大小,從小到大輸出,兩兩之間用空格分開.如果沒有解,則輸出"No Answer."(不含引號).
19
20
21
----樣例輸入:
22
23
12 54 34
24
4 2 4
25
26
27
----樣例輸出:
28
29
13 30
30
No Answer.
31
32
33
----分析:
34
35
[1]
36
擴展歐幾里得算法:
37
38
a * x + b * y = d (1)
39
d = gcd( a, b )
40
41
由
42
43
b * x1 + (a % b) * y1 = d
44
45
==>
46
47
b * x1 + (a - (a / b) * b) * y1 = d
48
49
==>
50
51
b * x1 + a * y1 - (a / b) * b * y1 = d
52
53
==>
54
55
a * y1 + b * (x1 - (a / b) * y1) = d (2)
56
57
58
比較 (1) 和 (2) 得
59
60
x = y1
61
y = x1 - (a / b) * y1
62
63
64
65
[2]
66
方程 ax≡b(mod m)
67
68
==>
69
70
ax + my = b
71
72
==>
73
74
當且僅當 b % gcd(a, m) == 0 時有解
75
76
77
*/
78
79
80
#include <iostream>
81
#include <cstdio>
82
#include <algorithm>
83
84
using namespace std;
85
86
#define N 1000009
87
88
typedef __int64 Lint;
89
90
int gcd( int a, int b ) {
91
int t;
92
while ( 0 != b ) {
93
t = a;
94
a = b;
95
b = t % b;
96
}
97
return a;
98
}
99
100
int gcd_ex( int a, int b, int &x, int &y ) {
101
if ( b == 0 ) {
102
x = 1;
103
y = 0;
104
return a;
105
}
106
int d = gcd_ex( b, a % b, x, y );
107
int t = x;
108
x = y;
109
y = (int)(t - ( a / b ) * ((Lint)(y)));
110
return d;
111
}
112
113
int a, b, m;
114
115
int n, x[ N ];
116
117
int solve() {
118
int i, d, tx, ty;
119
Lint tmp;
120
d = gcd( a, m );
121
if ( b % d != 0 ) {
122
return 0;
123
}
124
gcd_ex( a / d, m / d, tx, ty );
125
tx *= b / d;
126
n = d;
127
for ( i = 0; i < n; ++i ) {
128
tmp = tx + m / d * ((Lint)(i));
129
if ( 0 > tmp ) {
130
x[ i ] = m - ( (-tmp) % m );
131
}
132
else {
133
x[ i ] = tmp % m;
134
}
135
}
136
sort( x, x + n );
137
return 1;
138
}
139
140
int main() {
141
int i;
142
while ( scanf( "%d%d%d", &a, &b, &m ) == 3 ) {
143
if ( solve() ) {
144
printf( "%d", x[ 0 ] );
145
for ( i = 1; i < n; ++i ) {
146
printf( " %d", x[ i ] );
147
}
148
printf( "\n" );
149
}
150
else {
151
puts( "No Answer." );
152
}
153
}
154
return 0;
155
}
156

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

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

posted on 2012-06-01 21:26 coreBugZJ 閱讀(796) 評論(0) 編輯 收藏 引用 所屬分類: ACM 、Algorithm 、Mathematics 、課內作業