biguint.rs 58 KB

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