biguint.rs 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199
  1. use std::borrow::Cow;
  2. use std::default::Default;
  3. use std::iter::repeat;
  4. use std::ops::{Add, BitAnd, BitOr, BitXor, Div, Mul, Neg, Rem, Shl, Shr, Sub,
  5. AddAssign, BitAndAssign, BitOrAssign, BitXorAssign, DivAssign,
  6. MulAssign, RemAssign, ShlAssign, ShrAssign, SubAssign};
  7. use std::str::{self, FromStr};
  8. use std::fmt;
  9. use std::cmp;
  10. use std::cmp::Ordering::{self, Less, Greater, Equal};
  11. use std::{f32, f64};
  12. use std::{u8, u64};
  13. use std::ascii::AsciiExt;
  14. #[cfg(feature = "serde")]
  15. use serde;
  16. use integer::Integer;
  17. use traits::{ToPrimitive, FromPrimitive, Float, Num, Unsigned, CheckedAdd, CheckedSub, CheckedMul,
  18. CheckedDiv, Zero, One};
  19. #[path = "algorithms.rs"]
  20. mod algorithms;
  21. pub use self::algorithms::big_digit;
  22. pub use self::big_digit::{BigDigit, DoubleBigDigit, ZERO_BIG_DIGIT};
  23. use self::algorithms::{mac_with_carry, mul3, scalar_mul, div_rem, div_rem_digit};
  24. use self::algorithms::{__add2, add2, sub2, sub2rev};
  25. use self::algorithms::{biguint_shl, biguint_shr};
  26. use self::algorithms::{cmp_slice, fls, ilog2};
  27. use UsizePromotion;
  28. use ParseBigIntError;
  29. #[cfg(test)]
  30. #[path = "tests/biguint.rs"]
  31. mod biguint_tests;
  32. /// A big unsigned integer type.
  33. ///
  34. /// A `BigUint`-typed value `BigUint { data: vec!(a, b, c) }` represents a number
  35. /// `(a + b * big_digit::BASE + c * big_digit::BASE^2)`.
  36. #[derive(Clone, Debug, Hash)]
  37. #[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
  38. pub struct BigUint {
  39. data: Vec<BigDigit>,
  40. }
  41. impl PartialEq for BigUint {
  42. #[inline]
  43. fn eq(&self, other: &BigUint) -> bool {
  44. match self.cmp(other) {
  45. Equal => true,
  46. _ => false,
  47. }
  48. }
  49. }
  50. impl Eq for BigUint {}
  51. impl PartialOrd for BigUint {
  52. #[inline]
  53. fn partial_cmp(&self, other: &BigUint) -> Option<Ordering> {
  54. Some(self.cmp(other))
  55. }
  56. }
  57. impl Ord for BigUint {
  58. #[inline]
  59. fn cmp(&self, other: &BigUint) -> Ordering {
  60. cmp_slice(&self.data[..], &other.data[..])
  61. }
  62. }
  63. impl Default for BigUint {
  64. #[inline]
  65. fn default() -> BigUint {
  66. Zero::zero()
  67. }
  68. }
  69. impl fmt::Display for BigUint {
  70. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  71. f.pad_integral(true, "", &self.to_str_radix(10))
  72. }
  73. }
  74. impl fmt::LowerHex for BigUint {
  75. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  76. f.pad_integral(true, "0x", &self.to_str_radix(16))
  77. }
  78. }
  79. impl fmt::UpperHex for BigUint {
  80. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  81. f.pad_integral(true, "0x", &self.to_str_radix(16).to_ascii_uppercase())
  82. }
  83. }
  84. impl fmt::Binary for BigUint {
  85. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  86. f.pad_integral(true, "0b", &self.to_str_radix(2))
  87. }
  88. }
  89. impl fmt::Octal for BigUint {
  90. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  91. f.pad_integral(true, "0o", &self.to_str_radix(8))
  92. }
  93. }
  94. impl FromStr for BigUint {
  95. type Err = ParseBigIntError;
  96. #[inline]
  97. fn from_str(s: &str) -> Result<BigUint, ParseBigIntError> {
  98. BigUint::from_str_radix(s, 10)
  99. }
  100. }
  101. // Convert from a power of two radix (bits == ilog2(radix)) where bits evenly divides
  102. // BigDigit::BITS
  103. fn from_bitwise_digits_le(v: &[u8], bits: usize) -> BigUint {
  104. debug_assert!(!v.is_empty() && bits <= 8 && big_digit::BITS % bits == 0);
  105. debug_assert!(v.iter().all(|&c| (c as BigDigit) < (1 << bits)));
  106. let digits_per_big_digit = big_digit::BITS / bits;
  107. let data = v.chunks(digits_per_big_digit)
  108. .map(|chunk| {
  109. chunk.iter().rev().fold(0, |acc, &c| (acc << bits) | c as BigDigit)
  110. })
  111. .collect();
  112. BigUint::new(data)
  113. }
  114. // Convert from a power of two radix (bits == ilog2(radix)) where bits doesn't evenly divide
  115. // BigDigit::BITS
  116. fn from_inexact_bitwise_digits_le(v: &[u8], bits: usize) -> BigUint {
  117. debug_assert!(!v.is_empty() && bits <= 8 && big_digit::BITS % bits != 0);
  118. debug_assert!(v.iter().all(|&c| (c as BigDigit) < (1 << bits)));
  119. let big_digits = (v.len() * bits + big_digit::BITS - 1) / big_digit::BITS;
  120. let mut data = Vec::with_capacity(big_digits);
  121. let mut d = 0;
  122. let mut dbits = 0; // number of bits we currently have in d
  123. // walk v accumululating bits in d; whenever we accumulate big_digit::BITS in d, spit out a
  124. // big_digit:
  125. for &c in v {
  126. d |= (c as BigDigit) << dbits;
  127. dbits += bits;
  128. if dbits >= big_digit::BITS {
  129. data.push(d);
  130. dbits -= big_digit::BITS;
  131. // if dbits was > big_digit::BITS, we dropped some of the bits in c (they couldn't fit
  132. // in d) - grab the bits we lost here:
  133. d = (c as BigDigit) >> (bits - dbits);
  134. }
  135. }
  136. if dbits > 0 {
  137. debug_assert!(dbits < big_digit::BITS);
  138. data.push(d as BigDigit);
  139. }
  140. BigUint::new(data)
  141. }
  142. // Read little-endian radix digits
  143. fn from_radix_digits_be(v: &[u8], radix: u32) -> BigUint {
  144. debug_assert!(!v.is_empty() && !radix.is_power_of_two());
  145. debug_assert!(v.iter().all(|&c| (c as u32) < radix));
  146. // Estimate how big the result will be, so we can pre-allocate it.
  147. let bits = (radix as f64).log2() * v.len() as f64;
  148. let big_digits = (bits / big_digit::BITS as f64).ceil();
  149. let mut data = Vec::with_capacity(big_digits as usize);
  150. let (base, power) = get_radix_base(radix);
  151. let radix = radix as BigDigit;
  152. let r = v.len() % power;
  153. let i = if r == 0 {
  154. power
  155. } else {
  156. r
  157. };
  158. let (head, tail) = v.split_at(i);
  159. let first = head.iter().fold(0, |acc, &d| acc * radix + d as BigDigit);
  160. data.push(first);
  161. debug_assert!(tail.len() % power == 0);
  162. for chunk in tail.chunks(power) {
  163. if data.last() != Some(&0) {
  164. data.push(0);
  165. }
  166. let mut carry = 0;
  167. for d in data.iter_mut() {
  168. *d = mac_with_carry(0, *d, base, &mut carry);
  169. }
  170. debug_assert!(carry == 0);
  171. let n = chunk.iter().fold(0, |acc, &d| acc * radix + d as BigDigit);
  172. add2(&mut data, &[n]);
  173. }
  174. BigUint::new(data)
  175. }
  176. impl Num for BigUint {
  177. type FromStrRadixErr = ParseBigIntError;
  178. /// Creates and initializes a `BigUint`.
  179. fn from_str_radix(s: &str, radix: u32) -> Result<BigUint, ParseBigIntError> {
  180. assert!(2 <= radix && radix <= 36, "The radix must be within 2...36");
  181. let mut s = s;
  182. if s.starts_with('+') {
  183. let tail = &s[1..];
  184. if !tail.starts_with('+') {
  185. s = tail
  186. }
  187. }
  188. if s.is_empty() {
  189. // create ParseIntError::Empty
  190. let e = u64::from_str_radix(s, radix).unwrap_err();
  191. return Err(e.into());
  192. }
  193. // First normalize all characters to plain digit values
  194. let mut v = Vec::with_capacity(s.len());
  195. for b in s.bytes() {
  196. let d = match b {
  197. b'0'...b'9' => b - b'0',
  198. b'a'...b'z' => b - b'a' + 10,
  199. b'A'...b'Z' => b - b'A' + 10,
  200. _ => u8::MAX,
  201. };
  202. if d < radix as u8 {
  203. v.push(d);
  204. } else {
  205. // create ParseIntError::InvalidDigit
  206. // Include the previous character for context.
  207. let i = cmp::max(v.len(), 1) - 1;
  208. let e = u64::from_str_radix(&s[i..], radix).unwrap_err();
  209. return Err(e.into());
  210. }
  211. }
  212. let res = if radix.is_power_of_two() {
  213. // Powers of two can use bitwise masks and shifting instead of multiplication
  214. let bits = ilog2(radix);
  215. v.reverse();
  216. if big_digit::BITS % bits == 0 {
  217. from_bitwise_digits_le(&v, bits)
  218. } else {
  219. from_inexact_bitwise_digits_le(&v, bits)
  220. }
  221. } else {
  222. from_radix_digits_be(&v, radix)
  223. };
  224. Ok(res)
  225. }
  226. }
  227. forward_all_binop_to_val_ref_commutative!(impl BitAnd for BigUint, bitand);
  228. forward_val_assign!(impl BitAndAssign for BigUint, bitand_assign);
  229. impl<'a> BitAnd<&'a BigUint> for BigUint {
  230. type Output = BigUint;
  231. #[inline]
  232. fn bitand(mut self, other: &BigUint) -> BigUint {
  233. self &= other;
  234. self
  235. }
  236. }
  237. impl<'a> BitAndAssign<&'a BigUint> for BigUint {
  238. #[inline]
  239. fn bitand_assign(&mut self, other: &BigUint) {
  240. for (ai, &bi) in self.data.iter_mut().zip(other.data.iter()) {
  241. *ai &= bi;
  242. }
  243. self.data.truncate(other.data.len());
  244. self.normalize();
  245. }
  246. }
  247. forward_all_binop_to_val_ref_commutative!(impl BitOr for BigUint, bitor);
  248. forward_val_assign!(impl BitOrAssign for BigUint, bitor_assign);
  249. impl<'a> BitOr<&'a BigUint> for BigUint {
  250. type Output = BigUint;
  251. fn bitor(mut self, other: &BigUint) -> BigUint {
  252. self |= other;
  253. self
  254. }
  255. }
  256. impl<'a> BitOrAssign<&'a BigUint> for BigUint {
  257. #[inline]
  258. fn bitor_assign(&mut self, other: &BigUint) {
  259. for (ai, &bi) in self.data.iter_mut().zip(other.data.iter()) {
  260. *ai |= bi;
  261. }
  262. if other.data.len() > self.data.len() {
  263. let extra = &other.data[self.data.len()..];
  264. self.data.extend(extra.iter().cloned());
  265. }
  266. }
  267. }
  268. forward_all_binop_to_val_ref_commutative!(impl BitXor for BigUint, bitxor);
  269. forward_val_assign!(impl BitXorAssign for BigUint, bitxor_assign);
  270. impl<'a> BitXor<&'a BigUint> for BigUint {
  271. type Output = BigUint;
  272. fn bitxor(mut self, other: &BigUint) -> BigUint {
  273. self ^= other;
  274. self
  275. }
  276. }
  277. impl<'a> BitXorAssign<&'a BigUint> for BigUint {
  278. #[inline]
  279. fn bitxor_assign(&mut self, other: &BigUint) {
  280. for (ai, &bi) in self.data.iter_mut().zip(other.data.iter()) {
  281. *ai ^= bi;
  282. }
  283. if other.data.len() > self.data.len() {
  284. let extra = &other.data[self.data.len()..];
  285. self.data.extend(extra.iter().cloned());
  286. }
  287. self.normalize();
  288. }
  289. }
  290. impl Shl<usize> for BigUint {
  291. type Output = BigUint;
  292. #[inline]
  293. fn shl(self, rhs: usize) -> BigUint {
  294. biguint_shl(Cow::Owned(self), rhs)
  295. }
  296. }
  297. impl<'a> Shl<usize> for &'a BigUint {
  298. type Output = BigUint;
  299. #[inline]
  300. fn shl(self, rhs: usize) -> BigUint {
  301. biguint_shl(Cow::Borrowed(self), rhs)
  302. }
  303. }
  304. impl ShlAssign<usize> for BigUint {
  305. #[inline]
  306. fn shl_assign(&mut self, rhs: usize) {
  307. *self = biguint_shl(Cow::Borrowed(&*self), rhs);
  308. }
  309. }
  310. impl Shr<usize> for BigUint {
  311. type Output = BigUint;
  312. #[inline]
  313. fn shr(self, rhs: usize) -> BigUint {
  314. biguint_shr(Cow::Owned(self), rhs)
  315. }
  316. }
  317. impl<'a> Shr<usize> for &'a BigUint {
  318. type Output = BigUint;
  319. #[inline]
  320. fn shr(self, rhs: usize) -> BigUint {
  321. biguint_shr(Cow::Borrowed(self), rhs)
  322. }
  323. }
  324. impl ShrAssign<usize> for BigUint {
  325. #[inline]
  326. fn shr_assign(&mut self, rhs: usize) {
  327. *self = biguint_shr(Cow::Borrowed(&*self), rhs);
  328. }
  329. }
  330. impl Zero for BigUint {
  331. #[inline]
  332. fn zero() -> BigUint {
  333. BigUint::new(Vec::new())
  334. }
  335. #[inline]
  336. fn is_zero(&self) -> bool {
  337. self.data.is_empty()
  338. }
  339. }
  340. impl One for BigUint {
  341. #[inline]
  342. fn one() -> BigUint {
  343. BigUint::new(vec![1])
  344. }
  345. }
  346. impl Unsigned for BigUint {}
  347. forward_all_binop_to_val_ref_commutative!(impl Add for BigUint, add);
  348. forward_val_assign!(impl AddAssign for BigUint, add_assign);
  349. impl<'a> Add<&'a BigUint> for BigUint {
  350. type Output = BigUint;
  351. fn add(mut self, other: &BigUint) -> BigUint {
  352. self += other;
  353. self
  354. }
  355. }
  356. impl<'a> AddAssign<&'a BigUint> for BigUint {
  357. #[inline]
  358. fn add_assign(&mut self, other: &BigUint) {
  359. if self.data.len() < other.data.len() {
  360. let extra = other.data.len() - self.data.len();
  361. self.data.extend(repeat(0).take(extra));
  362. }
  363. let carry = __add2(&mut self.data[..], &other.data[..]);
  364. if carry != 0 {
  365. self.data.push(carry);
  366. }
  367. }
  368. }
  369. promote_unsigned_scalars!(impl Add for BigUint, add);
  370. promote_unsigned_scalars_assign!(impl AddAssign for BigUint, add_assign);
  371. forward_all_scalar_binop_to_val_val_commutative!(impl Add<BigDigit> for BigUint, add);
  372. forward_all_scalar_binop_to_val_val_commutative!(impl Add<DoubleBigDigit> for BigUint, add);
  373. impl Add<BigDigit> for BigUint {
  374. type Output = BigUint;
  375. #[inline]
  376. fn add(mut self, other: BigDigit) -> BigUint {
  377. self += other;
  378. self
  379. }
  380. }
  381. impl AddAssign<BigDigit> for BigUint {
  382. #[inline]
  383. fn add_assign(&mut self, other: BigDigit) {
  384. if other != 0 {
  385. if self.data.len() == 0 {
  386. self.data.push(0);
  387. }
  388. let carry = __add2(&mut self.data, &[other]);
  389. if carry != 0 {
  390. self.data.push(carry);
  391. }
  392. }
  393. }
  394. }
  395. impl Add<DoubleBigDigit> for BigUint {
  396. type Output = BigUint;
  397. #[inline]
  398. fn add(mut self, other: DoubleBigDigit) -> BigUint {
  399. self += other;
  400. self
  401. }
  402. }
  403. impl AddAssign<DoubleBigDigit> for BigUint {
  404. #[inline]
  405. fn add_assign(&mut self, other: DoubleBigDigit) {
  406. let (hi, lo) = big_digit::from_doublebigdigit(other);
  407. if hi == 0 {
  408. *self += lo;
  409. } else {
  410. while self.data.len() < 2 {
  411. self.data.push(0);
  412. }
  413. let carry = __add2(&mut self.data, &[lo, hi]);
  414. if carry != 0 {
  415. self.data.push(carry);
  416. }
  417. }
  418. }
  419. }
  420. forward_val_val_binop!(impl Sub for BigUint, sub);
  421. forward_ref_ref_binop!(impl Sub for BigUint, sub);
  422. forward_val_assign!(impl SubAssign for BigUint, sub_assign);
  423. impl<'a> Sub<&'a BigUint> for BigUint {
  424. type Output = BigUint;
  425. fn sub(mut self, other: &BigUint) -> BigUint {
  426. self -= other;
  427. self
  428. }
  429. }
  430. impl<'a> SubAssign<&'a BigUint> for BigUint {
  431. fn sub_assign(&mut self, other: &'a BigUint) {
  432. sub2(&mut self.data[..], &other.data[..]);
  433. self.normalize();
  434. }
  435. }
  436. impl<'a> Sub<BigUint> for &'a BigUint {
  437. type Output = BigUint;
  438. fn sub(self, mut other: BigUint) -> BigUint {
  439. if other.data.len() < self.data.len() {
  440. let extra = self.data.len() - other.data.len();
  441. other.data.extend(repeat(0).take(extra));
  442. }
  443. sub2rev(&self.data[..], &mut other.data[..]);
  444. other.normalized()
  445. }
  446. }
  447. promote_unsigned_scalars!(impl Sub for BigUint, sub);
  448. promote_unsigned_scalars_assign!(impl SubAssign for BigUint, sub_assign);
  449. forward_all_scalar_binop_to_val_val!(impl Sub<BigDigit> for BigUint, sub);
  450. forward_all_scalar_binop_to_val_val!(impl Sub<DoubleBigDigit> for BigUint, sub);
  451. impl Sub<BigDigit> for BigUint {
  452. type Output = BigUint;
  453. #[inline]
  454. fn sub(mut self, other: BigDigit) -> BigUint {
  455. self -= other;
  456. self
  457. }
  458. }
  459. impl SubAssign<BigDigit> for BigUint {
  460. fn sub_assign(&mut self, other: BigDigit) {
  461. sub2(&mut self.data[..], &[other]);
  462. self.normalize();
  463. }
  464. }
  465. impl Sub<BigUint> for BigDigit {
  466. type Output = BigUint;
  467. #[inline]
  468. fn sub(self, mut other: BigUint) -> BigUint {
  469. if other.data.len() == 0 {
  470. other.data.push(0);
  471. }
  472. sub2rev(&[self], &mut other.data[..]);
  473. other.normalized()
  474. }
  475. }
  476. impl Sub<DoubleBigDigit> for BigUint {
  477. type Output = BigUint;
  478. #[inline]
  479. fn sub(mut self, other: DoubleBigDigit) -> BigUint {
  480. self -= other;
  481. self
  482. }
  483. }
  484. impl SubAssign<DoubleBigDigit> for BigUint {
  485. fn sub_assign(&mut self, other: DoubleBigDigit) {
  486. let (hi, lo) = big_digit::from_doublebigdigit(other);
  487. sub2(&mut self.data[..], &[lo, hi]);
  488. self.normalize();
  489. }
  490. }
  491. impl Sub<BigUint> for DoubleBigDigit {
  492. type Output = BigUint;
  493. #[inline]
  494. fn sub(self, mut other: BigUint) -> BigUint {
  495. while other.data.len() < 2 {
  496. other.data.push(0);
  497. }
  498. let (hi, lo) = big_digit::from_doublebigdigit(self);
  499. sub2rev(&[lo, hi], &mut other.data[..]);
  500. other.normalized()
  501. }
  502. }
  503. forward_all_binop_to_ref_ref!(impl Mul for BigUint, mul);
  504. forward_val_assign!(impl MulAssign for BigUint, mul_assign);
  505. impl<'a, 'b> Mul<&'b BigUint> for &'a BigUint {
  506. type Output = BigUint;
  507. #[inline]
  508. fn mul(self, other: &BigUint) -> BigUint {
  509. mul3(&self.data[..], &other.data[..])
  510. }
  511. }
  512. impl<'a> MulAssign<&'a BigUint> for BigUint {
  513. #[inline]
  514. fn mul_assign(&mut self, other: &'a BigUint) {
  515. *self = &*self * other
  516. }
  517. }
  518. promote_unsigned_scalars!(impl Mul for BigUint, mul);
  519. promote_unsigned_scalars_assign!(impl MulAssign for BigUint, mul_assign);
  520. forward_all_scalar_binop_to_val_val_commutative!(impl Mul<BigDigit> for BigUint, mul);
  521. forward_all_scalar_binop_to_val_val_commutative!(impl Mul<DoubleBigDigit> for BigUint, mul);
  522. impl Mul<BigDigit> for BigUint {
  523. type Output = BigUint;
  524. #[inline]
  525. fn mul(mut self, other: BigDigit) -> BigUint {
  526. self *= other;
  527. self
  528. }
  529. }
  530. impl MulAssign<BigDigit> for BigUint {
  531. #[inline]
  532. fn mul_assign(&mut self, other: BigDigit) {
  533. if other == 0 {
  534. self.data.clear();
  535. } else {
  536. let carry = scalar_mul(&mut self.data[..], other);
  537. if carry != 0 {
  538. self.data.push(carry);
  539. }
  540. }
  541. }
  542. }
  543. impl Mul<DoubleBigDigit> for BigUint {
  544. type Output = BigUint;
  545. #[inline]
  546. fn mul(mut self, other: DoubleBigDigit) -> BigUint {
  547. self *= other;
  548. self
  549. }
  550. }
  551. impl MulAssign<DoubleBigDigit> for BigUint {
  552. #[inline]
  553. fn mul_assign(&mut self, other: DoubleBigDigit) {
  554. if other == 0 {
  555. self.data.clear();
  556. } else if other <= BigDigit::max_value() as DoubleBigDigit {
  557. *self *= other as BigDigit
  558. } else {
  559. let (hi, lo) = big_digit::from_doublebigdigit(other);
  560. *self = mul3(&self.data[..], &[lo, hi])
  561. }
  562. }
  563. }
  564. forward_all_binop_to_ref_ref!(impl Div for BigUint, div);
  565. forward_val_assign!(impl DivAssign for BigUint, div_assign);
  566. impl<'a, 'b> Div<&'b BigUint> for &'a BigUint {
  567. type Output = BigUint;
  568. #[inline]
  569. fn div(self, other: &BigUint) -> BigUint {
  570. let (q, _) = self.div_rem(other);
  571. q
  572. }
  573. }
  574. impl<'a> DivAssign<&'a BigUint> for BigUint {
  575. #[inline]
  576. fn div_assign(&mut self, other: &'a BigUint) {
  577. *self = &*self / other;
  578. }
  579. }
  580. promote_unsigned_scalars!(impl Div for BigUint, div);
  581. promote_unsigned_scalars_assign!(impl DivAssign for BigUint, div_assign);
  582. forward_all_scalar_binop_to_val_val!(impl Div<BigDigit> for BigUint, div);
  583. forward_all_scalar_binop_to_val_val!(impl Div<DoubleBigDigit> for BigUint, div);
  584. impl Div<BigDigit> for BigUint {
  585. type Output = BigUint;
  586. #[inline]
  587. fn div(self, other: BigDigit) -> BigUint {
  588. let (q, _) = div_rem_digit(self, other);
  589. q
  590. }
  591. }
  592. impl DivAssign<BigDigit> for BigUint {
  593. #[inline]
  594. fn div_assign(&mut self, other: BigDigit) {
  595. *self = &*self / other;
  596. }
  597. }
  598. impl Div<BigUint> for BigDigit {
  599. type Output = BigUint;
  600. #[inline]
  601. fn div(self, other: BigUint) -> BigUint {
  602. match other.data.len() {
  603. 0 => panic!(),
  604. 1 => From::from(self / other.data[0]),
  605. _ => Zero::zero(),
  606. }
  607. }
  608. }
  609. impl Div<DoubleBigDigit> for BigUint {
  610. type Output = BigUint;
  611. #[inline]
  612. fn div(self, other: DoubleBigDigit) -> BigUint {
  613. let (q, _) = self.div_rem(&From::from(other));
  614. q
  615. }
  616. }
  617. impl DivAssign<DoubleBigDigit> for BigUint {
  618. #[inline]
  619. fn div_assign(&mut self, other: DoubleBigDigit) {
  620. *self = &*self / other;
  621. }
  622. }
  623. impl Div<BigUint> for DoubleBigDigit {
  624. type Output = BigUint;
  625. #[inline]
  626. fn div(self, other: BigUint) -> BigUint {
  627. match other.data.len() {
  628. 0 => panic!(),
  629. 1 => From::from(self / other.data[0] as u64),
  630. 2 => From::from(self / big_digit::to_doublebigdigit(other.data[1], other.data[0])),
  631. _ => Zero::zero(),
  632. }
  633. }
  634. }
  635. forward_all_binop_to_ref_ref!(impl Rem for BigUint, rem);
  636. forward_val_assign!(impl RemAssign for BigUint, rem_assign);
  637. impl<'a, 'b> Rem<&'b BigUint> for &'a BigUint {
  638. type Output = BigUint;
  639. #[inline]
  640. fn rem(self, other: &BigUint) -> BigUint {
  641. let (_, r) = self.div_rem(other);
  642. r
  643. }
  644. }
  645. impl<'a> RemAssign<&'a BigUint> for BigUint {
  646. #[inline]
  647. fn rem_assign(&mut self, other: &BigUint) {
  648. *self = &*self % other;
  649. }
  650. }
  651. promote_unsigned_scalars!(impl Rem for BigUint, rem);
  652. promote_unsigned_scalars_assign!(impl RemAssign for BigUint, rem_assign);
  653. forward_all_scalar_binop_to_val_val!(impl Rem<BigDigit> for BigUint, rem);
  654. forward_all_scalar_binop_to_val_val!(impl Rem<DoubleBigDigit> for BigUint, rem);
  655. impl Rem<BigDigit> for BigUint {
  656. type Output = BigUint;
  657. #[inline]
  658. fn rem(self, other: BigDigit) -> BigUint {
  659. let (_, r) = div_rem_digit(self, other);
  660. From::from(r)
  661. }
  662. }
  663. impl RemAssign<BigDigit> for BigUint {
  664. #[inline]
  665. fn rem_assign(&mut self, other: BigDigit) {
  666. *self = &*self % other;
  667. }
  668. }
  669. impl Rem<BigUint> for BigDigit {
  670. type Output = BigUint;
  671. #[inline]
  672. fn rem(mut self, other: BigUint) -> BigUint {
  673. self %= other;
  674. From::from(self)
  675. }
  676. }
  677. macro_rules! impl_rem_assign_scalar {
  678. ($scalar:ty, $to_scalar:ident) => {
  679. forward_val_assign_scalar!(impl RemAssign for BigUint, $scalar, rem_assign);
  680. impl<'a> RemAssign<&'a BigUint> for $scalar {
  681. #[inline]
  682. fn rem_assign(&mut self, other: &BigUint) {
  683. *self = match other.$to_scalar() {
  684. None => *self,
  685. Some(0) => panic!(),
  686. Some(v) => *self % v
  687. };
  688. }
  689. }
  690. }
  691. }
  692. // we can scalar %= BigUint for any scalar, including signed types
  693. impl_rem_assign_scalar!(usize, to_usize);
  694. impl_rem_assign_scalar!(u64, to_u64);
  695. impl_rem_assign_scalar!(u32, to_u32);
  696. impl_rem_assign_scalar!(u16, to_u16);
  697. impl_rem_assign_scalar!(u8, to_u8);
  698. impl_rem_assign_scalar!(isize, to_isize);
  699. impl_rem_assign_scalar!(i64, to_i64);
  700. impl_rem_assign_scalar!(i32, to_i32);
  701. impl_rem_assign_scalar!(i16, to_i16);
  702. impl_rem_assign_scalar!(i8, to_i8);
  703. impl Rem<DoubleBigDigit> for BigUint {
  704. type Output = BigUint;
  705. #[inline]
  706. fn rem(self, other: DoubleBigDigit) -> BigUint {
  707. let (_, r) = self.div_rem(&From::from(other));
  708. r
  709. }
  710. }
  711. impl RemAssign<DoubleBigDigit> for BigUint {
  712. #[inline]
  713. fn rem_assign(&mut self, other: DoubleBigDigit) {
  714. *self = &*self % other;
  715. }
  716. }
  717. impl Rem<BigUint> for DoubleBigDigit {
  718. type Output = BigUint;
  719. #[inline]
  720. fn rem(mut self, other: BigUint) -> BigUint {
  721. self %= other;
  722. From::from(self)
  723. }
  724. }
  725. impl Neg for BigUint {
  726. type Output = BigUint;
  727. #[inline]
  728. fn neg(self) -> BigUint {
  729. panic!()
  730. }
  731. }
  732. impl<'a> Neg for &'a BigUint {
  733. type Output = BigUint;
  734. #[inline]
  735. fn neg(self) -> BigUint {
  736. panic!()
  737. }
  738. }
  739. impl CheckedAdd for BigUint {
  740. #[inline]
  741. fn checked_add(&self, v: &BigUint) -> Option<BigUint> {
  742. return Some(self.add(v));
  743. }
  744. }
  745. impl CheckedSub for BigUint {
  746. #[inline]
  747. fn checked_sub(&self, v: &BigUint) -> Option<BigUint> {
  748. match self.cmp(v) {
  749. Less => None,
  750. Equal => Some(Zero::zero()),
  751. Greater => Some(self.sub(v)),
  752. }
  753. }
  754. }
  755. impl CheckedMul for BigUint {
  756. #[inline]
  757. fn checked_mul(&self, v: &BigUint) -> Option<BigUint> {
  758. return Some(self.mul(v));
  759. }
  760. }
  761. impl CheckedDiv for BigUint {
  762. #[inline]
  763. fn checked_div(&self, v: &BigUint) -> Option<BigUint> {
  764. if v.is_zero() {
  765. return None;
  766. }
  767. return Some(self.div(v));
  768. }
  769. }
  770. impl Integer for BigUint {
  771. #[inline]
  772. fn div_rem(&self, other: &BigUint) -> (BigUint, BigUint) {
  773. div_rem(self, other)
  774. }
  775. #[inline]
  776. fn div_floor(&self, other: &BigUint) -> BigUint {
  777. let (d, _) = div_rem(self, other);
  778. d
  779. }
  780. #[inline]
  781. fn mod_floor(&self, other: &BigUint) -> BigUint {
  782. let (_, m) = div_rem(self, other);
  783. m
  784. }
  785. #[inline]
  786. fn div_mod_floor(&self, other: &BigUint) -> (BigUint, BigUint) {
  787. div_rem(self, other)
  788. }
  789. /// Calculates the Greatest Common Divisor (GCD) of the number and `other`.
  790. ///
  791. /// The result is always positive.
  792. #[inline]
  793. fn gcd(&self, other: &BigUint) -> BigUint {
  794. // Use Euclid's algorithm
  795. let mut m = (*self).clone();
  796. let mut n = (*other).clone();
  797. while !m.is_zero() {
  798. let temp = m;
  799. m = n % &temp;
  800. n = temp;
  801. }
  802. return n;
  803. }
  804. /// Calculates the Lowest Common Multiple (LCM) of the number and `other`.
  805. #[inline]
  806. fn lcm(&self, other: &BigUint) -> BigUint {
  807. ((self * other) / self.gcd(other))
  808. }
  809. /// Deprecated, use `is_multiple_of` instead.
  810. #[inline]
  811. fn divides(&self, other: &BigUint) -> bool {
  812. self.is_multiple_of(other)
  813. }
  814. /// Returns `true` if the number is a multiple of `other`.
  815. #[inline]
  816. fn is_multiple_of(&self, other: &BigUint) -> bool {
  817. (self % other).is_zero()
  818. }
  819. /// Returns `true` if the number is divisible by `2`.
  820. #[inline]
  821. fn is_even(&self) -> bool {
  822. // Considering only the last digit.
  823. match self.data.first() {
  824. Some(x) => x.is_even(),
  825. None => true,
  826. }
  827. }
  828. /// Returns `true` if the number is not divisible by `2`.
  829. #[inline]
  830. fn is_odd(&self) -> bool {
  831. !self.is_even()
  832. }
  833. }
  834. fn high_bits_to_u64(v: &BigUint) -> u64 {
  835. match v.data.len() {
  836. 0 => 0,
  837. 1 => v.data[0] as u64,
  838. _ => {
  839. let mut bits = v.bits();
  840. let mut ret = 0u64;
  841. let mut ret_bits = 0;
  842. for d in v.data.iter().rev() {
  843. let digit_bits = (bits - 1) % big_digit::BITS + 1;
  844. let bits_want = cmp::min(64 - ret_bits, digit_bits);
  845. if bits_want != 64 {
  846. ret <<= bits_want;
  847. }
  848. ret |= *d as u64 >> (digit_bits - bits_want);
  849. ret_bits += bits_want;
  850. bits -= bits_want;
  851. if ret_bits == 64 {
  852. break;
  853. }
  854. }
  855. ret
  856. }
  857. }
  858. }
  859. impl ToPrimitive for BigUint {
  860. #[inline]
  861. fn to_i64(&self) -> Option<i64> {
  862. self.to_u64().and_then(|n| {
  863. // If top bit of u64 is set, it's too large to convert to i64.
  864. if n >> 63 == 0 {
  865. Some(n as i64)
  866. } else {
  867. None
  868. }
  869. })
  870. }
  871. #[inline]
  872. fn to_u64(&self) -> Option<u64> {
  873. let mut ret: u64 = 0;
  874. let mut bits = 0;
  875. for i in self.data.iter() {
  876. if bits >= 64 {
  877. return None;
  878. }
  879. ret += (*i as u64) << bits;
  880. bits += big_digit::BITS;
  881. }
  882. Some(ret)
  883. }
  884. #[inline]
  885. fn to_f32(&self) -> Option<f32> {
  886. let mantissa = high_bits_to_u64(self);
  887. let exponent = self.bits() - fls(mantissa);
  888. if exponent > f32::MAX_EXP as usize {
  889. None
  890. } else {
  891. let ret = (mantissa as f32) * 2.0f32.powi(exponent as i32);
  892. if ret.is_infinite() {
  893. None
  894. } else {
  895. Some(ret)
  896. }
  897. }
  898. }
  899. #[inline]
  900. fn to_f64(&self) -> Option<f64> {
  901. let mantissa = high_bits_to_u64(self);
  902. let exponent = self.bits() - fls(mantissa);
  903. if exponent > f64::MAX_EXP as usize {
  904. None
  905. } else {
  906. let ret = (mantissa as f64) * 2.0f64.powi(exponent as i32);
  907. if ret.is_infinite() {
  908. None
  909. } else {
  910. Some(ret)
  911. }
  912. }
  913. }
  914. }
  915. impl FromPrimitive for BigUint {
  916. #[inline]
  917. fn from_i64(n: i64) -> Option<BigUint> {
  918. if n >= 0 {
  919. Some(BigUint::from(n as u64))
  920. } else {
  921. None
  922. }
  923. }
  924. #[inline]
  925. fn from_u64(n: u64) -> Option<BigUint> {
  926. Some(BigUint::from(n))
  927. }
  928. #[inline]
  929. fn from_f64(mut n: f64) -> Option<BigUint> {
  930. // handle NAN, INFINITY, NEG_INFINITY
  931. if !n.is_finite() {
  932. return None;
  933. }
  934. // match the rounding of casting from float to int
  935. n = n.trunc();
  936. // handle 0.x, -0.x
  937. if n.is_zero() {
  938. return Some(BigUint::zero());
  939. }
  940. let (mantissa, exponent, sign) = Float::integer_decode(n);
  941. if sign == -1 {
  942. return None;
  943. }
  944. let mut ret = BigUint::from(mantissa);
  945. if exponent > 0 {
  946. ret = ret << exponent as usize;
  947. } else if exponent < 0 {
  948. ret = ret >> (-exponent) as usize;
  949. }
  950. Some(ret)
  951. }
  952. }
  953. impl From<u64> for BigUint {
  954. #[inline]
  955. fn from(mut n: u64) -> Self {
  956. let mut ret: BigUint = Zero::zero();
  957. while n != 0 {
  958. ret.data.push(n as BigDigit);
  959. // don't overflow if BITS is 64:
  960. n = (n >> 1) >> (big_digit::BITS - 1);
  961. }
  962. ret
  963. }
  964. }
  965. macro_rules! impl_biguint_from_uint {
  966. ($T:ty) => {
  967. impl From<$T> for BigUint {
  968. #[inline]
  969. fn from(n: $T) -> Self {
  970. BigUint::from(n as u64)
  971. }
  972. }
  973. }
  974. }
  975. impl_biguint_from_uint!(u8);
  976. impl_biguint_from_uint!(u16);
  977. impl_biguint_from_uint!(u32);
  978. impl_biguint_from_uint!(usize);
  979. /// A generic trait for converting a value to a `BigUint`.
  980. pub trait ToBigUint {
  981. /// Converts the value of `self` to a `BigUint`.
  982. fn to_biguint(&self) -> Option<BigUint>;
  983. }
  984. impl ToBigUint for BigUint {
  985. #[inline]
  986. fn to_biguint(&self) -> Option<BigUint> {
  987. Some(self.clone())
  988. }
  989. }
  990. macro_rules! impl_to_biguint {
  991. ($T:ty, $from_ty:path) => {
  992. impl ToBigUint for $T {
  993. #[inline]
  994. fn to_biguint(&self) -> Option<BigUint> {
  995. $from_ty(*self)
  996. }
  997. }
  998. }
  999. }
  1000. impl_to_biguint!(isize, FromPrimitive::from_isize);
  1001. impl_to_biguint!(i8, FromPrimitive::from_i8);
  1002. impl_to_biguint!(i16, FromPrimitive::from_i16);
  1003. impl_to_biguint!(i32, FromPrimitive::from_i32);
  1004. impl_to_biguint!(i64, FromPrimitive::from_i64);
  1005. impl_to_biguint!(usize, FromPrimitive::from_usize);
  1006. impl_to_biguint!(u8, FromPrimitive::from_u8);
  1007. impl_to_biguint!(u16, FromPrimitive::from_u16);
  1008. impl_to_biguint!(u32, FromPrimitive::from_u32);
  1009. impl_to_biguint!(u64, FromPrimitive::from_u64);
  1010. impl_to_biguint!(f32, FromPrimitive::from_f32);
  1011. impl_to_biguint!(f64, FromPrimitive::from_f64);
  1012. // Extract bitwise digits that evenly divide BigDigit
  1013. fn to_bitwise_digits_le(u: &BigUint, bits: usize) -> Vec<u8> {
  1014. debug_assert!(!u.is_zero() && bits <= 8 && big_digit::BITS % bits == 0);
  1015. let last_i = u.data.len() - 1;
  1016. let mask: BigDigit = (1 << bits) - 1;
  1017. let digits_per_big_digit = big_digit::BITS / bits;
  1018. let digits = (u.bits() + bits - 1) / bits;
  1019. let mut res = Vec::with_capacity(digits);
  1020. for mut r in u.data[..last_i].iter().cloned() {
  1021. for _ in 0..digits_per_big_digit {
  1022. res.push((r & mask) as u8);
  1023. r >>= bits;
  1024. }
  1025. }
  1026. let mut r = u.data[last_i];
  1027. while r != 0 {
  1028. res.push((r & mask) as u8);
  1029. r >>= bits;
  1030. }
  1031. res
  1032. }
  1033. // Extract bitwise digits that don't evenly divide BigDigit
  1034. fn to_inexact_bitwise_digits_le(u: &BigUint, bits: usize) -> Vec<u8> {
  1035. debug_assert!(!u.is_zero() && bits <= 8 && big_digit::BITS % bits != 0);
  1036. let mask: BigDigit = (1 << bits) - 1;
  1037. let digits = (u.bits() + bits - 1) / bits;
  1038. let mut res = Vec::with_capacity(digits);
  1039. let mut r = 0;
  1040. let mut rbits = 0;
  1041. for c in &u.data {
  1042. r |= *c << rbits;
  1043. rbits += big_digit::BITS;
  1044. while rbits >= bits {
  1045. res.push((r & mask) as u8);
  1046. r >>= bits;
  1047. // r had more bits than it could fit - grab the bits we lost
  1048. if rbits > big_digit::BITS {
  1049. r = *c >> (big_digit::BITS - (rbits - bits));
  1050. }
  1051. rbits -= bits;
  1052. }
  1053. }
  1054. if rbits != 0 {
  1055. res.push(r as u8);
  1056. }
  1057. while let Some(&0) = res.last() {
  1058. res.pop();
  1059. }
  1060. res
  1061. }
  1062. // Extract little-endian radix digits
  1063. #[inline(always)] // forced inline to get const-prop for radix=10
  1064. fn to_radix_digits_le(u: &BigUint, radix: u32) -> Vec<u8> {
  1065. debug_assert!(!u.is_zero() && !radix.is_power_of_two());
  1066. // Estimate how big the result will be, so we can pre-allocate it.
  1067. let radix_digits = ((u.bits() as f64) / (radix as f64).log2()).ceil();
  1068. let mut res = Vec::with_capacity(radix_digits as usize);
  1069. let mut digits = u.clone();
  1070. let (base, power) = get_radix_base(radix);
  1071. let radix = radix as BigDigit;
  1072. while digits.data.len() > 1 {
  1073. let (q, mut r) = div_rem_digit(digits, base);
  1074. for _ in 0..power {
  1075. res.push((r % radix) as u8);
  1076. r /= radix;
  1077. }
  1078. digits = q;
  1079. }
  1080. let mut r = digits.data[0];
  1081. while r != 0 {
  1082. res.push((r % radix) as u8);
  1083. r /= radix;
  1084. }
  1085. res
  1086. }
  1087. pub fn to_radix_le(u: &BigUint, radix: u32) -> Vec<u8> {
  1088. if u.is_zero() {
  1089. vec![0]
  1090. } else if radix.is_power_of_two() {
  1091. // Powers of two can use bitwise masks and shifting instead of division
  1092. let bits = ilog2(radix);
  1093. if big_digit::BITS % bits == 0 {
  1094. to_bitwise_digits_le(u, bits)
  1095. } else {
  1096. to_inexact_bitwise_digits_le(u, bits)
  1097. }
  1098. } else if radix == 10 {
  1099. // 10 is so common that it's worth separating out for const-propagation.
  1100. // Optimizers can often turn constant division into a faster multiplication.
  1101. to_radix_digits_le(u, 10)
  1102. } else {
  1103. to_radix_digits_le(u, radix)
  1104. }
  1105. }
  1106. pub fn to_str_radix_reversed(u: &BigUint, radix: u32) -> Vec<u8> {
  1107. assert!(2 <= radix && radix <= 36, "The radix must be within 2...36");
  1108. if u.is_zero() {
  1109. return vec![b'0'];
  1110. }
  1111. let mut res = to_radix_le(u, radix);
  1112. // Now convert everything to ASCII digits.
  1113. for r in &mut res {
  1114. debug_assert!((*r as u32) < radix);
  1115. if *r < 10 {
  1116. *r += b'0';
  1117. } else {
  1118. *r += b'a' - 10;
  1119. }
  1120. }
  1121. res
  1122. }
  1123. impl BigUint {
  1124. /// Creates and initializes a `BigUint`.
  1125. ///
  1126. /// The digits are in little-endian base 2^32.
  1127. #[inline]
  1128. pub fn new(digits: Vec<BigDigit>) -> BigUint {
  1129. BigUint { data: digits }.normalized()
  1130. }
  1131. /// Creates and initializes a `BigUint`.
  1132. ///
  1133. /// The digits are in little-endian base 2^32.
  1134. #[inline]
  1135. pub fn from_slice(slice: &[BigDigit]) -> BigUint {
  1136. BigUint::new(slice.to_vec())
  1137. }
  1138. /// Assign a value to a `BigUint`.
  1139. ///
  1140. /// The digits are in little-endian base 2^32.
  1141. #[inline]
  1142. pub fn assign_from_slice(&mut self, slice: &[BigDigit]) {
  1143. self.data.resize(slice.len(), 0);
  1144. self.data.clone_from_slice(slice);
  1145. self.normalize();
  1146. }
  1147. /// Creates and initializes a `BigUint`.
  1148. ///
  1149. /// The bytes are in big-endian byte order.
  1150. ///
  1151. /// # Examples
  1152. ///
  1153. /// ```
  1154. /// use num_bigint::BigUint;
  1155. ///
  1156. /// assert_eq!(BigUint::from_bytes_be(b"A"),
  1157. /// BigUint::parse_bytes(b"65", 10).unwrap());
  1158. /// assert_eq!(BigUint::from_bytes_be(b"AA"),
  1159. /// BigUint::parse_bytes(b"16705", 10).unwrap());
  1160. /// assert_eq!(BigUint::from_bytes_be(b"AB"),
  1161. /// BigUint::parse_bytes(b"16706", 10).unwrap());
  1162. /// assert_eq!(BigUint::from_bytes_be(b"Hello world!"),
  1163. /// BigUint::parse_bytes(b"22405534230753963835153736737", 10).unwrap());
  1164. /// ```
  1165. #[inline]
  1166. pub fn from_bytes_be(bytes: &[u8]) -> BigUint {
  1167. if bytes.is_empty() {
  1168. Zero::zero()
  1169. } else {
  1170. let mut v = bytes.to_vec();
  1171. v.reverse();
  1172. BigUint::from_bytes_le(&*v)
  1173. }
  1174. }
  1175. /// Creates and initializes a `BigUint`.
  1176. ///
  1177. /// The bytes are in little-endian byte order.
  1178. #[inline]
  1179. pub fn from_bytes_le(bytes: &[u8]) -> BigUint {
  1180. if bytes.is_empty() {
  1181. Zero::zero()
  1182. } else {
  1183. from_bitwise_digits_le(bytes, 8)
  1184. }
  1185. }
  1186. /// Creates and initializes a `BigUint`. The input slice must contain
  1187. /// ascii/utf8 characters in [0-9a-zA-Z].
  1188. /// `radix` must be in the range `2...36`.
  1189. ///
  1190. /// The function `from_str_radix` from the `Num` trait provides the same logic
  1191. /// for `&str` buffers.
  1192. ///
  1193. /// # Examples
  1194. ///
  1195. /// ```
  1196. /// use num_bigint::{BigUint, ToBigUint};
  1197. ///
  1198. /// assert_eq!(BigUint::parse_bytes(b"1234", 10), ToBigUint::to_biguint(&1234));
  1199. /// assert_eq!(BigUint::parse_bytes(b"ABCD", 16), ToBigUint::to_biguint(&0xABCD));
  1200. /// assert_eq!(BigUint::parse_bytes(b"G", 16), None);
  1201. /// ```
  1202. #[inline]
  1203. pub fn parse_bytes(buf: &[u8], radix: u32) -> Option<BigUint> {
  1204. str::from_utf8(buf).ok().and_then(|s| BigUint::from_str_radix(s, radix).ok())
  1205. }
  1206. /// Creates and initializes a `BigUint`. Each u8 of the input slice is
  1207. /// interpreted as one digit of the number
  1208. /// and must therefore be less than `radix`.
  1209. ///
  1210. /// The bytes are in big-endian byte order.
  1211. /// `radix` must be in the range `2...256`.
  1212. ///
  1213. /// # Examples
  1214. ///
  1215. /// ```
  1216. /// use num_bigint::{BigUint};
  1217. ///
  1218. /// let inbase190 = &[15, 33, 125, 12, 14];
  1219. /// let a = BigUint::from_radix_be(inbase190, 190).unwrap();
  1220. /// assert_eq!(a.to_radix_be(190), inbase190);
  1221. /// ```
  1222. pub fn from_radix_be(buf: &[u8], radix: u32) -> Option<BigUint> {
  1223. assert!(2 <= radix && radix <= 256, "The radix must be within 2...256");
  1224. if radix != 256 && buf.iter().any(|&b| b >= radix as u8) {
  1225. return None;
  1226. }
  1227. let res = if radix.is_power_of_two() {
  1228. // Powers of two can use bitwise masks and shifting instead of multiplication
  1229. let bits = ilog2(radix);
  1230. let mut v = Vec::from(buf);
  1231. v.reverse();
  1232. if big_digit::BITS % bits == 0 {
  1233. from_bitwise_digits_le(&v, bits)
  1234. } else {
  1235. from_inexact_bitwise_digits_le(&v, bits)
  1236. }
  1237. } else {
  1238. from_radix_digits_be(buf, radix)
  1239. };
  1240. Some(res)
  1241. }
  1242. /// Creates and initializes a `BigUint`. Each u8 of the input slice is
  1243. /// interpreted as one digit of the number
  1244. /// and must therefore be less than `radix`.
  1245. ///
  1246. /// The bytes are in little-endian byte order.
  1247. /// `radix` must be in the range `2...256`.
  1248. ///
  1249. /// # Examples
  1250. ///
  1251. /// ```
  1252. /// use num_bigint::{BigUint};
  1253. ///
  1254. /// let inbase190 = &[14, 12, 125, 33, 15];
  1255. /// let a = BigUint::from_radix_be(inbase190, 190).unwrap();
  1256. /// assert_eq!(a.to_radix_be(190), inbase190);
  1257. /// ```
  1258. pub fn from_radix_le(buf: &[u8], radix: u32) -> Option<BigUint> {
  1259. assert!(2 <= radix && radix <= 256, "The radix must be within 2...256");
  1260. if radix != 256 && buf.iter().any(|&b| b >= radix as u8) {
  1261. return None;
  1262. }
  1263. let res = if radix.is_power_of_two() {
  1264. // Powers of two can use bitwise masks and shifting instead of multiplication
  1265. let bits = ilog2(radix);
  1266. if big_digit::BITS % bits == 0 {
  1267. from_bitwise_digits_le(buf, bits)
  1268. } else {
  1269. from_inexact_bitwise_digits_le(buf, bits)
  1270. }
  1271. } else {
  1272. let mut v = Vec::from(buf);
  1273. v.reverse();
  1274. from_radix_digits_be(&v, radix)
  1275. };
  1276. Some(res)
  1277. }
  1278. /// Returns the byte representation of the `BigUint` in big-endian byte order.
  1279. ///
  1280. /// # Examples
  1281. ///
  1282. /// ```
  1283. /// use num_bigint::BigUint;
  1284. ///
  1285. /// let i = BigUint::parse_bytes(b"1125", 10).unwrap();
  1286. /// assert_eq!(i.to_bytes_be(), vec![4, 101]);
  1287. /// ```
  1288. #[inline]
  1289. pub fn to_bytes_be(&self) -> Vec<u8> {
  1290. let mut v = self.to_bytes_le();
  1291. v.reverse();
  1292. v
  1293. }
  1294. /// Returns the byte representation of the `BigUint` in little-endian byte order.
  1295. ///
  1296. /// # Examples
  1297. ///
  1298. /// ```
  1299. /// use num_bigint::BigUint;
  1300. ///
  1301. /// let i = BigUint::parse_bytes(b"1125", 10).unwrap();
  1302. /// assert_eq!(i.to_bytes_le(), vec![101, 4]);
  1303. /// ```
  1304. #[inline]
  1305. pub fn to_bytes_le(&self) -> Vec<u8> {
  1306. if self.is_zero() {
  1307. vec![0]
  1308. } else {
  1309. to_bitwise_digits_le(self, 8)
  1310. }
  1311. }
  1312. /// Returns the integer formatted as a string in the given radix.
  1313. /// `radix` must be in the range `2...36`.
  1314. ///
  1315. /// # Examples
  1316. ///
  1317. /// ```
  1318. /// use num_bigint::BigUint;
  1319. ///
  1320. /// let i = BigUint::parse_bytes(b"ff", 16).unwrap();
  1321. /// assert_eq!(i.to_str_radix(16), "ff");
  1322. /// ```
  1323. #[inline]
  1324. pub fn to_str_radix(&self, radix: u32) -> String {
  1325. let mut v = to_str_radix_reversed(self, radix);
  1326. v.reverse();
  1327. unsafe { String::from_utf8_unchecked(v) }
  1328. }
  1329. /// Returns the integer in the requested base in big-endian digit order.
  1330. /// The output is not given in a human readable alphabet but as a zero
  1331. /// based u8 number.
  1332. /// `radix` must be in the range `2...256`.
  1333. ///
  1334. /// # Examples
  1335. ///
  1336. /// ```
  1337. /// use num_bigint::BigUint;
  1338. ///
  1339. /// assert_eq!(BigUint::from(0xFFFFu64).to_radix_be(159),
  1340. /// vec![2, 94, 27]);
  1341. /// // 0xFFFF = 65535 = 2*(159^2) + 94*159 + 27
  1342. /// ```
  1343. #[inline]
  1344. pub fn to_radix_be(&self, radix: u32) -> Vec<u8> {
  1345. let mut v = to_radix_le(self, radix);
  1346. v.reverse();
  1347. v
  1348. }
  1349. /// Returns the integer in the requested base in little-endian digit order.
  1350. /// The output is not given in a human readable alphabet but as a zero
  1351. /// based u8 number.
  1352. /// `radix` must be in the range `2...256`.
  1353. ///
  1354. /// # Examples
  1355. ///
  1356. /// ```
  1357. /// use num_bigint::BigUint;
  1358. ///
  1359. /// assert_eq!(BigUint::from(0xFFFFu64).to_radix_le(159),
  1360. /// vec![27, 94, 2]);
  1361. /// // 0xFFFF = 65535 = 27 + 94*159 + 2*(159^2)
  1362. /// ```
  1363. #[inline]
  1364. pub fn to_radix_le(&self, radix: u32) -> Vec<u8> {
  1365. to_radix_le(self, radix)
  1366. }
  1367. /// Determines the fewest bits necessary to express the `BigUint`.
  1368. #[inline]
  1369. pub fn bits(&self) -> usize {
  1370. if self.is_zero() {
  1371. return 0;
  1372. }
  1373. let zeros = self.data.last().unwrap().leading_zeros();
  1374. return self.data.len() * big_digit::BITS - zeros as usize;
  1375. }
  1376. /// Strips off trailing zero bigdigits - comparisons require the last element in the vector to
  1377. /// be nonzero.
  1378. #[inline]
  1379. fn normalize(&mut self) {
  1380. while let Some(&0) = self.data.last() {
  1381. self.data.pop();
  1382. }
  1383. }
  1384. /// Returns a normalized `BigUint`.
  1385. #[inline]
  1386. fn normalized(mut self) -> BigUint {
  1387. self.normalize();
  1388. self
  1389. }
  1390. }
  1391. #[cfg(feature = "serde")]
  1392. impl serde::Serialize for BigUint {
  1393. fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
  1394. where S: serde::Serializer
  1395. {
  1396. self.data.serialize(serializer)
  1397. }
  1398. }
  1399. #[cfg(feature = "serde")]
  1400. impl serde::Deserialize for BigUint {
  1401. fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
  1402. where D: serde::Deserializer
  1403. {
  1404. let data = try!(Vec::deserialize(deserializer));
  1405. Ok(BigUint { data: data })
  1406. }
  1407. }
  1408. /// Returns the greatest power of the radix <= big_digit::BASE
  1409. #[inline]
  1410. fn get_radix_base(radix: u32) -> (BigDigit, usize) {
  1411. debug_assert!(2 <= radix && radix <= 256, "The radix must be within 2...256");
  1412. debug_assert!(!radix.is_power_of_two());
  1413. // To generate this table:
  1414. // for radix in 2u64..257 {
  1415. // let mut power = big_digit::BITS / fls(radix as u64);
  1416. // let mut base = radix.pow(power as u32);
  1417. //
  1418. // while let Some(b) = base.checked_mul(radix) {
  1419. // if b > big_digit::MAX {
  1420. // break;
  1421. // }
  1422. // base = b;
  1423. // power += 1;
  1424. // }
  1425. //
  1426. // println!("({:10}, {:2}), // {:2}", base, power, radix);
  1427. // }
  1428. // and
  1429. // for radix in 2u64..257 {
  1430. // let mut power = 64 / fls(radix as u64);
  1431. // let mut base = radix.pow(power as u32);
  1432. //
  1433. // while let Some(b) = base.checked_mul(radix) {
  1434. // base = b;
  1435. // power += 1;
  1436. // }
  1437. //
  1438. // println!("({:20}, {:2}), // {:2}", base, power, radix);
  1439. // }
  1440. match big_digit::BITS {
  1441. 32 => {
  1442. const BASES: [(u32, usize); 257] = [
  1443. ( 0, 0),
  1444. ( 0, 0),
  1445. ( 0, 0), // 2
  1446. (3486784401, 20), // 3
  1447. ( 0, 0), // 4
  1448. (1220703125, 13), // 5
  1449. (2176782336, 12), // 6
  1450. (1977326743, 11), // 7
  1451. ( 0, 0), // 8
  1452. (3486784401, 10), // 9
  1453. (1000000000, 9), // 10
  1454. (2357947691, 9), // 11
  1455. ( 429981696, 8), // 12
  1456. ( 815730721, 8), // 13
  1457. (1475789056, 8), // 14
  1458. (2562890625, 8), // 15
  1459. ( 0, 0), // 16
  1460. ( 410338673, 7), // 17
  1461. ( 612220032, 7), // 18
  1462. ( 893871739, 7), // 19
  1463. (1280000000, 7), // 20
  1464. (1801088541, 7), // 21
  1465. (2494357888, 7), // 22
  1466. (3404825447, 7), // 23
  1467. ( 191102976, 6), // 24
  1468. ( 244140625, 6), // 25
  1469. ( 308915776, 6), // 26
  1470. ( 387420489, 6), // 27
  1471. ( 481890304, 6), // 28
  1472. ( 594823321, 6), // 29
  1473. ( 729000000, 6), // 30
  1474. ( 887503681, 6), // 31
  1475. ( 0, 0), // 32
  1476. (1291467969, 6), // 33
  1477. (1544804416, 6), // 34
  1478. (1838265625, 6), // 35
  1479. (2176782336, 6), // 36
  1480. (2565726409, 6), // 37
  1481. (3010936384, 6), // 38
  1482. (3518743761, 6), // 39
  1483. (4096000000, 6), // 40
  1484. ( 115856201, 5), // 41
  1485. ( 130691232, 5), // 42
  1486. ( 147008443, 5), // 43
  1487. ( 164916224, 5), // 44
  1488. ( 184528125, 5), // 45
  1489. ( 205962976, 5), // 46
  1490. ( 229345007, 5), // 47
  1491. ( 254803968, 5), // 48
  1492. ( 282475249, 5), // 49
  1493. ( 312500000, 5), // 50
  1494. ( 345025251, 5), // 51
  1495. ( 380204032, 5), // 52
  1496. ( 418195493, 5), // 53
  1497. ( 459165024, 5), // 54
  1498. ( 503284375, 5), // 55
  1499. ( 550731776, 5), // 56
  1500. ( 601692057, 5), // 57
  1501. ( 656356768, 5), // 58
  1502. ( 714924299, 5), // 59
  1503. ( 777600000, 5), // 60
  1504. ( 844596301, 5), // 61
  1505. ( 916132832, 5), // 62
  1506. ( 992436543, 5), // 63
  1507. ( 0, 0), // 64
  1508. (1160290625, 5), // 65
  1509. (1252332576, 5), // 66
  1510. (1350125107, 5), // 67
  1511. (1453933568, 5), // 68
  1512. (1564031349, 5), // 69
  1513. (1680700000, 5), // 70
  1514. (1804229351, 5), // 71
  1515. (1934917632, 5), // 72
  1516. (2073071593, 5), // 73
  1517. (2219006624, 5), // 74
  1518. (2373046875, 5), // 75
  1519. (2535525376, 5), // 76
  1520. (2706784157, 5), // 77
  1521. (2887174368, 5), // 78
  1522. (3077056399, 5), // 79
  1523. (3276800000, 5), // 80
  1524. (3486784401, 5), // 81
  1525. (3707398432, 5), // 82
  1526. (3939040643, 5), // 83
  1527. (4182119424, 5), // 84
  1528. ( 52200625, 4), // 85
  1529. ( 54700816, 4), // 86
  1530. ( 57289761, 4), // 87
  1531. ( 59969536, 4), // 88
  1532. ( 62742241, 4), // 89
  1533. ( 65610000, 4), // 90
  1534. ( 68574961, 4), // 91
  1535. ( 71639296, 4), // 92
  1536. ( 74805201, 4), // 93
  1537. ( 78074896, 4), // 94
  1538. ( 81450625, 4), // 95
  1539. ( 84934656, 4), // 96
  1540. ( 88529281, 4), // 97
  1541. ( 92236816, 4), // 98
  1542. ( 96059601, 4), // 99
  1543. ( 100000000, 4), // 100
  1544. ( 104060401, 4), // 101
  1545. ( 108243216, 4), // 102
  1546. ( 112550881, 4), // 103
  1547. ( 116985856, 4), // 104
  1548. ( 121550625, 4), // 105
  1549. ( 126247696, 4), // 106
  1550. ( 131079601, 4), // 107
  1551. ( 136048896, 4), // 108
  1552. ( 141158161, 4), // 109
  1553. ( 146410000, 4), // 110
  1554. ( 151807041, 4), // 111
  1555. ( 157351936, 4), // 112
  1556. ( 163047361, 4), // 113
  1557. ( 168896016, 4), // 114
  1558. ( 174900625, 4), // 115
  1559. ( 181063936, 4), // 116
  1560. ( 187388721, 4), // 117
  1561. ( 193877776, 4), // 118
  1562. ( 200533921, 4), // 119
  1563. ( 207360000, 4), // 120
  1564. ( 214358881, 4), // 121
  1565. ( 221533456, 4), // 122
  1566. ( 228886641, 4), // 123
  1567. ( 236421376, 4), // 124
  1568. ( 244140625, 4), // 125
  1569. ( 252047376, 4), // 126
  1570. ( 260144641, 4), // 127
  1571. ( 0, 0), // 128
  1572. ( 276922881, 4), // 129
  1573. ( 285610000, 4), // 130
  1574. ( 294499921, 4), // 131
  1575. ( 303595776, 4), // 132
  1576. ( 312900721, 4), // 133
  1577. ( 322417936, 4), // 134
  1578. ( 332150625, 4), // 135
  1579. ( 342102016, 4), // 136
  1580. ( 352275361, 4), // 137
  1581. ( 362673936, 4), // 138
  1582. ( 373301041, 4), // 139
  1583. ( 384160000, 4), // 140
  1584. ( 395254161, 4), // 141
  1585. ( 406586896, 4), // 142
  1586. ( 418161601, 4), // 143
  1587. ( 429981696, 4), // 144
  1588. ( 442050625, 4), // 145
  1589. ( 454371856, 4), // 146
  1590. ( 466948881, 4), // 147
  1591. ( 479785216, 4), // 148
  1592. ( 492884401, 4), // 149
  1593. ( 506250000, 4), // 150
  1594. ( 519885601, 4), // 151
  1595. ( 533794816, 4), // 152
  1596. ( 547981281, 4), // 153
  1597. ( 562448656, 4), // 154
  1598. ( 577200625, 4), // 155
  1599. ( 592240896, 4), // 156
  1600. ( 607573201, 4), // 157
  1601. ( 623201296, 4), // 158
  1602. ( 639128961, 4), // 159
  1603. ( 655360000, 4), // 160
  1604. ( 671898241, 4), // 161
  1605. ( 688747536, 4), // 162
  1606. ( 705911761, 4), // 163
  1607. ( 723394816, 4), // 164
  1608. ( 741200625, 4), // 165
  1609. ( 759333136, 4), // 166
  1610. ( 777796321, 4), // 167
  1611. ( 796594176, 4), // 168
  1612. ( 815730721, 4), // 169
  1613. ( 835210000, 4), // 170
  1614. ( 855036081, 4), // 171
  1615. ( 875213056, 4), // 172
  1616. ( 895745041, 4), // 173
  1617. ( 916636176, 4), // 174
  1618. ( 937890625, 4), // 175
  1619. ( 959512576, 4), // 176
  1620. ( 981506241, 4), // 177
  1621. (1003875856, 4), // 178
  1622. (1026625681, 4), // 179
  1623. (1049760000, 4), // 180
  1624. (1073283121, 4), // 181
  1625. (1097199376, 4), // 182
  1626. (1121513121, 4), // 183
  1627. (1146228736, 4), // 184
  1628. (1171350625, 4), // 185
  1629. (1196883216, 4), // 186
  1630. (1222830961, 4), // 187
  1631. (1249198336, 4), // 188
  1632. (1275989841, 4), // 189
  1633. (1303210000, 4), // 190
  1634. (1330863361, 4), // 191
  1635. (1358954496, 4), // 192
  1636. (1387488001, 4), // 193
  1637. (1416468496, 4), // 194
  1638. (1445900625, 4), // 195
  1639. (1475789056, 4), // 196
  1640. (1506138481, 4), // 197
  1641. (1536953616, 4), // 198
  1642. (1568239201, 4), // 199
  1643. (1600000000, 4), // 200
  1644. (1632240801, 4), // 201
  1645. (1664966416, 4), // 202
  1646. (1698181681, 4), // 203
  1647. (1731891456, 4), // 204
  1648. (1766100625, 4), // 205
  1649. (1800814096, 4), // 206
  1650. (1836036801, 4), // 207
  1651. (1871773696, 4), // 208
  1652. (1908029761, 4), // 209
  1653. (1944810000, 4), // 210
  1654. (1982119441, 4), // 211
  1655. (2019963136, 4), // 212
  1656. (2058346161, 4), // 213
  1657. (2097273616, 4), // 214
  1658. (2136750625, 4), // 215
  1659. (2176782336, 4), // 216
  1660. (2217373921, 4), // 217
  1661. (2258530576, 4), // 218
  1662. (2300257521, 4), // 219
  1663. (2342560000, 4), // 220
  1664. (2385443281, 4), // 221
  1665. (2428912656, 4), // 222
  1666. (2472973441, 4), // 223
  1667. (2517630976, 4), // 224
  1668. (2562890625, 4), // 225
  1669. (2608757776, 4), // 226
  1670. (2655237841, 4), // 227
  1671. (2702336256, 4), // 228
  1672. (2750058481, 4), // 229
  1673. (2798410000, 4), // 230
  1674. (2847396321, 4), // 231
  1675. (2897022976, 4), // 232
  1676. (2947295521, 4), // 233
  1677. (2998219536, 4), // 234
  1678. (3049800625, 4), // 235
  1679. (3102044416, 4), // 236
  1680. (3154956561, 4), // 237
  1681. (3208542736, 4), // 238
  1682. (3262808641, 4), // 239
  1683. (3317760000, 4), // 240
  1684. (3373402561, 4), // 241
  1685. (3429742096, 4), // 242
  1686. (3486784401, 4), // 243
  1687. (3544535296, 4), // 244
  1688. (3603000625, 4), // 245
  1689. (3662186256, 4), // 246
  1690. (3722098081, 4), // 247
  1691. (3782742016, 4), // 248
  1692. (3844124001, 4), // 249
  1693. (3906250000, 4), // 250
  1694. (3969126001, 4), // 251
  1695. (4032758016, 4), // 252
  1696. (4097152081, 4), // 253
  1697. (4162314256, 4), // 254
  1698. (4228250625, 4), // 255
  1699. ( 0, 0), // 256
  1700. ];
  1701. let (base, power) = BASES[radix as usize];
  1702. (base as BigDigit, power)
  1703. }
  1704. 64 => {
  1705. const BASES: [(u64, usize); 257] = [
  1706. ( 0, 0),
  1707. ( 0, 0),
  1708. ( 9223372036854775808, 63), // 2
  1709. (12157665459056928801, 40), // 3
  1710. ( 4611686018427387904, 31), // 4
  1711. ( 7450580596923828125, 27), // 5
  1712. ( 4738381338321616896, 24), // 6
  1713. ( 3909821048582988049, 22), // 7
  1714. ( 9223372036854775808, 21), // 8
  1715. (12157665459056928801, 20), // 9
  1716. (10000000000000000000, 19), // 10
  1717. ( 5559917313492231481, 18), // 11
  1718. ( 2218611106740436992, 17), // 12
  1719. ( 8650415919381337933, 17), // 13
  1720. ( 2177953337809371136, 16), // 14
  1721. ( 6568408355712890625, 16), // 15
  1722. ( 1152921504606846976, 15), // 16
  1723. ( 2862423051509815793, 15), // 17
  1724. ( 6746640616477458432, 15), // 18
  1725. (15181127029874798299, 15), // 19
  1726. ( 1638400000000000000, 14), // 20
  1727. ( 3243919932521508681, 14), // 21
  1728. ( 6221821273427820544, 14), // 22
  1729. (11592836324538749809, 14), // 23
  1730. ( 876488338465357824, 13), // 24
  1731. ( 1490116119384765625, 13), // 25
  1732. ( 2481152873203736576, 13), // 26
  1733. ( 4052555153018976267, 13), // 27
  1734. ( 6502111422497947648, 13), // 28
  1735. (10260628712958602189, 13), // 29
  1736. (15943230000000000000, 13), // 30
  1737. ( 787662783788549761, 12), // 31
  1738. ( 1152921504606846976, 12), // 32
  1739. ( 1667889514952984961, 12), // 33
  1740. ( 2386420683693101056, 12), // 34
  1741. ( 3379220508056640625, 12), // 35
  1742. ( 4738381338321616896, 12), // 36
  1743. ( 6582952005840035281, 12), // 37
  1744. ( 9065737908494995456, 12), // 38
  1745. (12381557655576425121, 12), // 39
  1746. (16777216000000000000, 12), // 40
  1747. ( 550329031716248441, 11), // 41
  1748. ( 717368321110468608, 11), // 42
  1749. ( 929293739471222707, 11), // 43
  1750. ( 1196683881290399744, 11), // 44
  1751. ( 1532278301220703125, 11), // 45
  1752. ( 1951354384207722496, 11), // 46
  1753. ( 2472159215084012303, 11), // 47
  1754. ( 3116402981210161152, 11), // 48
  1755. ( 3909821048582988049, 11), // 49
  1756. ( 4882812500000000000, 11), // 50
  1757. ( 6071163615208263051, 11), // 51
  1758. ( 7516865509350965248, 11), // 52
  1759. ( 9269035929372191597, 11), // 53
  1760. (11384956040305711104, 11), // 54
  1761. (13931233916552734375, 11), // 55
  1762. (16985107389382393856, 11), // 56
  1763. ( 362033331456891249, 10), // 57
  1764. ( 430804206899405824, 10), // 58
  1765. ( 511116753300641401, 10), // 59
  1766. ( 604661760000000000, 10), // 60
  1767. ( 713342911662882601, 10), // 61
  1768. ( 839299365868340224, 10), // 62
  1769. ( 984930291881790849, 10), // 63
  1770. ( 1152921504606846976, 10), // 64
  1771. ( 1346274334462890625, 10), // 65
  1772. ( 1568336880910795776, 10), // 66
  1773. ( 1822837804551761449, 10), // 67
  1774. ( 2113922820157210624, 10), // 68
  1775. ( 2446194060654759801, 10), // 69
  1776. ( 2824752490000000000, 10), // 70
  1777. ( 3255243551009881201, 10), // 71
  1778. ( 3743906242624487424, 10), // 72
  1779. ( 4297625829703557649, 10), // 73
  1780. ( 4923990397355877376, 10), // 74
  1781. ( 5631351470947265625, 10), // 75
  1782. ( 6428888932339941376, 10), // 76
  1783. ( 7326680472586200649, 10), // 77
  1784. ( 8335775831236199424, 10), // 78
  1785. ( 9468276082626847201, 10), // 79
  1786. (10737418240000000000, 10), // 80
  1787. (12157665459056928801, 10), // 81
  1788. (13744803133596058624, 10), // 82
  1789. (15516041187205853449, 10), // 83
  1790. (17490122876598091776, 10), // 84
  1791. ( 231616946283203125, 9), // 85
  1792. ( 257327417311663616, 9), // 86
  1793. ( 285544154243029527, 9), // 87
  1794. ( 316478381828866048, 9), // 88
  1795. ( 350356403707485209, 9), // 89
  1796. ( 387420489000000000, 9), // 90
  1797. ( 427929800129788411, 9), // 91
  1798. ( 472161363286556672, 9), // 92
  1799. ( 520411082988487293, 9), // 93
  1800. ( 572994802228616704, 9), // 94
  1801. ( 630249409724609375, 9), // 95
  1802. ( 692533995824480256, 9), // 96
  1803. ( 760231058654565217, 9), // 97
  1804. ( 833747762130149888, 9), // 98
  1805. ( 913517247483640899, 9), // 99
  1806. ( 1000000000000000000, 9), // 100
  1807. ( 1093685272684360901, 9), // 101
  1808. ( 1195092568622310912, 9), // 102
  1809. ( 1304773183829244583, 9), // 103
  1810. ( 1423311812421484544, 9), // 104
  1811. ( 1551328215978515625, 9), // 105
  1812. ( 1689478959002692096, 9), // 106
  1813. ( 1838459212420154507, 9), // 107
  1814. ( 1999004627104432128, 9), // 108
  1815. ( 2171893279442309389, 9), // 109
  1816. ( 2357947691000000000, 9), // 110
  1817. ( 2558036924386500591, 9), // 111
  1818. ( 2773078757450186752, 9), // 112
  1819. ( 3004041937984268273, 9), // 113
  1820. ( 3251948521156637184, 9), // 114
  1821. ( 3517876291919921875, 9), // 115
  1822. ( 3802961274698203136, 9), // 116
  1823. ( 4108400332687853397, 9), // 117
  1824. ( 4435453859151328768, 9), // 118
  1825. ( 4785448563124474679, 9), // 119
  1826. ( 5159780352000000000, 9), // 120
  1827. ( 5559917313492231481, 9), // 121
  1828. ( 5987402799531080192, 9), // 122
  1829. ( 6443858614676334363, 9), // 123
  1830. ( 6930988311686938624, 9), // 124
  1831. ( 7450580596923828125, 9), // 125
  1832. ( 8004512848309157376, 9), // 126
  1833. ( 8594754748609397887, 9), // 127
  1834. ( 9223372036854775808, 9), // 128
  1835. ( 9892530380752880769, 9), // 129
  1836. (10604499373000000000, 9), // 130
  1837. (11361656654439817571, 9), // 131
  1838. (12166492167065567232, 9), // 132
  1839. (13021612539908538853, 9), // 133
  1840. (13929745610903012864, 9), // 134
  1841. (14893745087865234375, 9), // 135
  1842. (15916595351771938816, 9), // 136
  1843. (17001416405572203977, 9), // 137
  1844. (18151468971815029248, 9), // 138
  1845. ( 139353667211683681, 8), // 139
  1846. ( 147578905600000000, 8), // 140
  1847. ( 156225851787813921, 8), // 141
  1848. ( 165312903998914816, 8), // 142
  1849. ( 174859124550883201, 8), // 143
  1850. ( 184884258895036416, 8), // 144
  1851. ( 195408755062890625, 8), // 145
  1852. ( 206453783524884736, 8), // 146
  1853. ( 218041257467152161, 8), // 147
  1854. ( 230193853492166656, 8), // 148
  1855. ( 242935032749128801, 8), // 149
  1856. ( 256289062500000000, 8), // 150
  1857. ( 270281038127131201, 8), // 151
  1858. ( 284936905588473856, 8), // 152
  1859. ( 300283484326400961, 8), // 153
  1860. ( 316348490636206336, 8), // 154
  1861. ( 333160561500390625, 8), // 155
  1862. ( 350749278894882816, 8), // 156
  1863. ( 369145194573386401, 8), // 157
  1864. ( 388379855336079616, 8), // 158
  1865. ( 408485828788939521, 8), // 159
  1866. ( 429496729600000000, 8), // 160
  1867. ( 451447246258894081, 8), // 161
  1868. ( 474373168346071296, 8), // 162
  1869. ( 498311414318121121, 8), // 163
  1870. ( 523300059815673856, 8), // 164
  1871. ( 549378366500390625, 8), // 165
  1872. ( 576586811427594496, 8), // 166
  1873. ( 604967116961135041, 8), // 167
  1874. ( 634562281237118976, 8), // 168
  1875. ( 665416609183179841, 8), // 169
  1876. ( 697575744100000000, 8), // 170
  1877. ( 731086699811838561, 8), // 171
  1878. ( 765997893392859136, 8), // 172
  1879. ( 802359178476091681, 8), // 173
  1880. ( 840221879151902976, 8), // 174
  1881. ( 879638824462890625, 8), // 175
  1882. ( 920664383502155776, 8), // 176
  1883. ( 963354501121950081, 8), // 177
  1884. ( 1007766734259732736, 8), // 178
  1885. ( 1053960288888713761, 8), // 179
  1886. ( 1101996057600000000, 8), // 180
  1887. ( 1151936657823500641, 8), // 181
  1888. ( 1203846470694789376, 8), // 182
  1889. ( 1257791680575160641, 8), // 183
  1890. ( 1313840315232157696, 8), // 184
  1891. ( 1372062286687890625, 8), // 185
  1892. ( 1432529432742502656, 8), // 186
  1893. ( 1495315559180183521, 8), // 187
  1894. ( 1560496482665168896, 8), // 188
  1895. ( 1628150074335205281, 8), // 189
  1896. ( 1698356304100000000, 8), // 190
  1897. ( 1771197285652216321, 8), // 191
  1898. ( 1846757322198614016, 8), // 192
  1899. ( 1925122952918976001, 8), // 193
  1900. ( 2006383000160502016, 8), // 194
  1901. ( 2090628617375390625, 8), // 195
  1902. ( 2177953337809371136, 8), // 196
  1903. ( 2268453123948987361, 8), // 197
  1904. ( 2362226417735475456, 8), // 198
  1905. ( 2459374191553118401, 8), // 199
  1906. ( 2560000000000000000, 8), // 200
  1907. ( 2664210032449121601, 8), // 201
  1908. ( 2772113166407885056, 8), // 202
  1909. ( 2883821021683985761, 8), // 203
  1910. ( 2999448015365799936, 8), // 204
  1911. ( 3119111417625390625, 8), // 205
  1912. ( 3242931408352297216, 8), // 206
  1913. ( 3371031134626313601, 8), // 207
  1914. ( 3503536769037500416, 8), // 208
  1915. ( 3640577568861717121, 8), // 209
  1916. ( 3782285936100000000, 8), // 210
  1917. ( 3928797478390152481, 8), // 211
  1918. ( 4080251070798954496, 8), // 212
  1919. ( 4236788918503437921, 8), // 213
  1920. ( 4398556620369715456, 8), // 214
  1921. ( 4565703233437890625, 8), // 215
  1922. ( 4738381338321616896, 8), // 216
  1923. ( 4916747105530914241, 8), // 217
  1924. ( 5100960362726891776, 8), // 218
  1925. ( 5291184662917065441, 8), // 219
  1926. ( 5487587353600000000, 8), // 220
  1927. ( 5690339646868044961, 8), // 221
  1928. ( 5899616690476974336, 8), // 222
  1929. ( 6115597639891380481, 8), // 223
  1930. ( 6338465731314712576, 8), // 224
  1931. ( 6568408355712890625, 8), // 225
  1932. ( 6805617133840466176, 8), // 226
  1933. ( 7050287992278341281, 8), // 227
  1934. ( 7302621240492097536, 8), // 228
  1935. ( 7562821648920027361, 8), // 229
  1936. ( 7831098528100000000, 8), // 230
  1937. ( 8107665808844335041, 8), // 231
  1938. ( 8392742123471896576, 8), // 232
  1939. ( 8686550888106661441, 8), // 233
  1940. ( 8989320386052055296, 8), // 234
  1941. ( 9301283852250390625, 8), // 235
  1942. ( 9622679558836781056, 8), // 236
  1943. ( 9953750901796946721, 8), // 237
  1944. (10294746488738365696, 8), // 238
  1945. (10645920227784266881, 8), // 239
  1946. (11007531417600000000, 8), // 240
  1947. (11379844838561358721, 8), // 241
  1948. (11763130845074473216, 8), // 242
  1949. (12157665459056928801, 8), // 243
  1950. (12563730464589807616, 8), // 244
  1951. (12981613503750390625, 8), // 245
  1952. (13411608173635297536, 8), // 246
  1953. (13854014124583882561, 8), // 247
  1954. (14309137159611744256, 8), // 248
  1955. (14777289335064248001, 8), // 249
  1956. (15258789062500000000, 8), // 250
  1957. (15753961211814252001, 8), // 251
  1958. (16263137215612256256, 8), // 252
  1959. (16786655174842630561, 8), // 253
  1960. (17324859965700833536, 8), // 254
  1961. (17878103347812890625, 8), // 255
  1962. ( 72057594037927936, 7), // 256
  1963. ];
  1964. let (base, power) = BASES[radix as usize];
  1965. (base as BigDigit, power)
  1966. }
  1967. _ => panic!("Invalid bigdigit size")
  1968. }
  1969. }