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
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
| #ifndef LONGLONG_CPP_INCLUDED
#define LONGLONG_CPP_INCLUDED
#include <stdexcept>
#include <string>
#include <algorithm>
#include "longlong.h"
const LongLong LongLong::c_zero = LongLong( 0, 0 );
const LongLong LongLong::c_one = LongLong( 0, 1 );
const LongLong LongLong::c_minus_one = -LongLong::c_one;
const LongLong LongLong::c_ten = LongLong( 0, 10 );
LongLong LongLong::operator - () const
{
return LongLong( ~_high, ~_low ) + c_one;
}
LongLong LongLong::operator = ( const LongLong& right )
{
_low = right._low;
_high = right._high;
return *this;
}
LongLong LongLong::operator + ( const LongLong& right ) const
{
low_type low = _low + right._low;
high_type high = _high + right._high;
// обработка переполнений
if( low < _low )
high++;
return LongLong( high, low );
}
LongLong LongLong::operator += ( const LongLong& right )
{
return *this = *this + right;
}
LongLong LongLong::operator - ( const LongLong& right ) const
{
low_type low = _low - right._low;
high_type high = _high - right._high;
// обработка переполнений
if( _low < right._low )
high--;
return LongLong( high, low );
}
LongLong LongLong::operator -= ( const LongLong& right )
{
return *this = *this - right;
}
LongLong LongLong::operator * ( const LongLong& right ) const
{
LongLong res( c_zero );
low_type lm = 1;
for( int d = 0; d < low_digits; d++, lm <<= 1 )
if( _low & lm )
res += right << d;
high_type hm = 1;
for( int d = low_digits; d < all_digits; d++, hm <<= 1 )
if( _high & hm )
res += right << d;
return res;
}
LongLong LongLong::operator *= ( const LongLong& right )
{
return *this = *this * right;
}
LongLong LongLong::operator / ( const LongLong& right ) const
{
LongLong quot, rem;
divMod( *this, right, quot, rem );
return quot;
}
LongLong LongLong::operator /= ( const LongLong& right )
{
return *this = *this / right;
}
LongLong LongLong::operator % ( const LongLong& right ) const
{
LongLong quot, rem;
divMod( *this, right, quot, rem );
return rem;
}
LongLong LongLong::operator %= ( const LongLong& right )
{
return *this = *this % right;
}
LongLong LongLong::operator << ( unsigned int s ) const
{
// сдвиг на 32 и больше бит может работать неправильно
high_type high1 = _high << s;
high_type high2 = ( unsigned_low_type )_low >> ( low_digits - s );
low_type low = _low << s;
// todo: opt
if( high_digits == 32 && s >= 32 )
high1 = 0;
if( low_digits == 32 )
{
if( s >= 32 )
low = 0;
if( low_digits >= s + 32 )
high2 = 0;
else if( s > low_digits )
high2 = ( unsigned_low_type )_low << ( s - low_digits );
}
return LongLong( high1 | high2, low );
}
LongLong LongLong::operator <<= ( unsigned int s )
{
return *this = *this << s;
}
LongLong LongLong::operator >> ( unsigned int s ) const
{
// сдвиг на 32 и больше бит может работать неправильно
high_type high = _high >> s;
low_type low1 = _high << ( low_digits - s );
low_type low2 = ( unsigned_low_type )_low >> s;
// todo: opt
if( high_digits == 32 && s >= 32 )
high = ( high < 0 ) ? -1 : 0;
if( low_digits == 32 )
{
if( low_digits < s )
low1 = _high >> ( s - low_digits );
if( s >= 32 )
low2 = 0;
}
return LongLong( high, low1 | low2 );
}
LongLong LongLong::operator >>= ( unsigned int s )
{
return *this = *this >> s;
}
bool LongLong::operator == ( const LongLong& right ) const
{
return _high == right._high && _low == right._low;
}
bool LongLong::operator != ( const LongLong& right ) const
{
return _high != right._high || _low != right._low;
}
bool LongLong::operator >= ( const LongLong& right ) const
{
if( _high > right._high )
return true;
if( _high < right._high )
return false;
return _low >= right._low;
}
bool LongLong::operator <= ( const LongLong& right ) const
{
if( _high < right._high )
return true;
if( _high > right._high )
return false;
return _low <= right._low;
}
bool LongLong::operator > ( const LongLong& right ) const
{
if( _high > right._high )
return true;
if( _high < right._high )
return false;
return _low > right._low;
}
bool LongLong::operator < ( const LongLong& right ) const
{
if( _high < right._high )
return true;
if( _high > right._high )
return false;
return _low < right._low;
}
std::string LongLong::toStringBin( bool postfix ) const
{
std::string s;
unsigned_high_type hm = 1 << ( high_digits - 1 );
unsigned_low_type lm = 1 << ( low_digits - 1 );
for( int d = high_digits - 1; d >= 0; d--, hm >>= 1 )
s += ( ( (unsigned_high_type)_high & hm ) != 0 ) ? '1' : '0';
for( int d = low_digits - 1; d >= 0; d--, lm >>= 1 )
s += ( ( (unsigned_low_type)_low & lm ) != 0 ) ? '1' : '0';
return s + ( postfix ? "b" : "" );
}
std::string LongLong::toStringHex( bool prefix ) const
{
static char hexs[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
int lhexs = low_digits / 4;
int hhexs = high_digits / 4;
unsigned_high_type hm = 0xf << ( high_digits - 4 );
unsigned_low_type lm = 0xf << ( low_digits - 4 );
std::string s( prefix ? "0x" : "" );
for( int h = 4*( hhexs - 1 ); h >= 0; h -= 4, hm >>= 4 )
s += hexs[( (unsigned_high_type)_high & hm ) >> h];
for( int h = 4*( lhexs - 1 ); h >= 0; h -= 4, lm >>= 4 )
s += hexs[( (unsigned_low_type)_low & lm ) >> h];
return s;
}
std::string LongLong::toStringDec() const
{
if( _high == 0 && _low == 0 )
return "0";
std::string s;
// проход от младших к старшим нужен, чтобы правильно обрабатывать старший разряд (0x80000000_00000000)
bool neg = *this < c_zero;
LongLong a( *this ); //neg ? -*this : *this;
LongLong d;
while( a != c_zero )
{
divMod( a, c_ten, a, d );
//d = neg ? ( - ( a % c_ten ) ) : ( a % c_ten );//!neg ? ( a - ( a / c_ten ) * c_ten ) : ( ( a / c_ten ) * c_ten - a );
//d = ( neg ? ( -d ) : d );
s += std::to_string( ( neg ? ( -d ) : d )._low );
//a /= c_ten; // todo: opt
}
s += neg ? "-" : "";
std::reverse( s.begin(), s.end() );
return s;
}
// совмещённая функция для вычисления сразу частного и остатка от деления
void LongLong::divMod( LongLong left, LongLong right, LongLong& quot, LongLong& rem )
{
if( right == c_zero )
throw std::runtime_error( "Division by zero" );
rem = left; // остаток
quot = c_zero; // частное
LongLong rr = rem >> 1; // для точного определения максимального скользящего делителя
LongLong div = right; // скользящий делитель
LongLong m; // маска
int sh = 0; // сдвиг
// в этом алгоритме нельзя брать -left, -right из-за значения 0x8000000000000000,
// обратное которому не влезает в наш LongLong,
// поэтому приходится расписывать 4 ветви:
if( rem >= c_zero )
{
if( div > c_zero )
{
m = c_one;
// проход вверх для поиска максимального скользящего делителя
while( div < rr )
{
div <<= 1;
m <<= 1;
sh++;
}
// проход вниз с нисходящим делением
while( sh >= 0 )
{
if( rem >= div )
{
rem -= div;
quot += m;
}
div >>= 1;
m >>= 1;
sh--;
}
} else // if( div < 0 )
{
// то же самое, только для других знаков
m = c_minus_one;
while( c_zero < rr + div )
{
div <<= 1;
m <<= 1;
sh++;
}
while( sh >= 0 )
{
if( rem + div >= c_zero )
{
rem += div;
quot += m;
}
div >>= 1;
m >>= 1;
sh--;
}
}
} else // if( rem < 0 )
{
// то же самое, только для других знаков
if( div > c_zero )
{
m = c_minus_one;
while( rr + div < c_zero )
{
div <<= 1;
m <<= 1;
sh++;
}
while( sh >= 0 )
{
if( c_zero >= rem + div )
{
rem += div;
quot += m;
}
div >>= 1;
m >>= 1;
sh--;
}
} else // if( div < 0 )
{
m = c_one;
while( div > rr )
{
div <<= 1;
m <<= 1;
sh++;
}
while( sh >= 0 )
{
if( rem <= div )
{
rem -= div;
quot += m;
}
div >>= 1;
m >>= 1;
sh--;
}
}
}
}
std::ostream& operator << ( std::ostream& ostr, const LongLong& ll )
{
std::ios::fmtflags fs = ostr.flags();
if( fs & std::ios::hex )
ostr << ll.toStringHex( ostr.flags() & ostr.showbase );
else if( fs & std::ios::dec )
ostr << ll.toStringDec();
else if( fs & std::ios::oct ) // при настройке потока на вывод восьмеричных чисел
ostr << ll.toStringBin( ostr.flags() & ostr.showbase ); // выводится двоичное представление
else
throw std::runtime_error( "Unknown base" );
return ostr;
}
#endif // LONGLONG_CPP_INCLUDED |