biguint.rs 69 KB

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