biguint.rs 63 KB

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