bigint.rs 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406
  1. use num_bigint::BigUint;
  2. use num_bigint::Sign::{Minus, NoSign, Plus};
  3. use num_bigint::{BigInt, ToBigInt};
  4. use std::cmp::Ordering::{Equal, Greater, Less};
  5. use std::collections::hash_map::RandomState;
  6. use std::hash::{BuildHasher, Hash, Hasher};
  7. use std::iter::repeat;
  8. use std::ops::Neg;
  9. use std::{f32, f64};
  10. use std::{i128, u128};
  11. use std::{i16, i32, i64, i8, isize};
  12. use std::{u16, u32, u64, u8, usize};
  13. use num_integer::Integer;
  14. use num_traits::{pow, FromPrimitive, Num, One, Pow, Signed, ToPrimitive, Zero};
  15. mod consts;
  16. use crate::consts::*;
  17. #[macro_use]
  18. mod macros;
  19. #[test]
  20. fn test_from_bytes_be() {
  21. fn check(s: &str, result: &str) {
  22. assert_eq!(
  23. BigInt::from_bytes_be(Plus, s.as_bytes()),
  24. BigInt::parse_bytes(result.as_bytes(), 10).unwrap()
  25. );
  26. }
  27. check("A", "65");
  28. check("AA", "16705");
  29. check("AB", "16706");
  30. check("Hello world!", "22405534230753963835153736737");
  31. assert_eq!(BigInt::from_bytes_be(Plus, &[]), BigInt::zero());
  32. assert_eq!(BigInt::from_bytes_be(Minus, &[]), BigInt::zero());
  33. }
  34. #[test]
  35. fn test_to_bytes_be() {
  36. fn check(s: &str, result: &str) {
  37. let b = BigInt::parse_bytes(result.as_bytes(), 10).unwrap();
  38. let (sign, v) = b.to_bytes_be();
  39. assert_eq!((Plus, s.as_bytes()), (sign, &*v));
  40. }
  41. check("A", "65");
  42. check("AA", "16705");
  43. check("AB", "16706");
  44. check("Hello world!", "22405534230753963835153736737");
  45. let b: BigInt = Zero::zero();
  46. assert_eq!(b.to_bytes_be(), (NoSign, vec![0]));
  47. // Test with leading/trailing zero bytes and a full BigDigit of value 0
  48. let b = BigInt::from_str_radix("00010000000000000200", 16).unwrap();
  49. assert_eq!(b.to_bytes_be(), (Plus, vec![1, 0, 0, 0, 0, 0, 0, 2, 0]));
  50. }
  51. #[test]
  52. fn test_from_bytes_le() {
  53. fn check(s: &str, result: &str) {
  54. assert_eq!(
  55. BigInt::from_bytes_le(Plus, s.as_bytes()),
  56. BigInt::parse_bytes(result.as_bytes(), 10).unwrap()
  57. );
  58. }
  59. check("A", "65");
  60. check("AA", "16705");
  61. check("BA", "16706");
  62. check("!dlrow olleH", "22405534230753963835153736737");
  63. assert_eq!(BigInt::from_bytes_le(Plus, &[]), BigInt::zero());
  64. assert_eq!(BigInt::from_bytes_le(Minus, &[]), BigInt::zero());
  65. }
  66. #[test]
  67. fn test_to_bytes_le() {
  68. fn check(s: &str, result: &str) {
  69. let b = BigInt::parse_bytes(result.as_bytes(), 10).unwrap();
  70. let (sign, v) = b.to_bytes_le();
  71. assert_eq!((Plus, s.as_bytes()), (sign, &*v));
  72. }
  73. check("A", "65");
  74. check("AA", "16705");
  75. check("BA", "16706");
  76. check("!dlrow olleH", "22405534230753963835153736737");
  77. let b: BigInt = Zero::zero();
  78. assert_eq!(b.to_bytes_le(), (NoSign, vec![0]));
  79. // Test with leading/trailing zero bytes and a full BigDigit of value 0
  80. let b = BigInt::from_str_radix("00010000000000000200", 16).unwrap();
  81. assert_eq!(b.to_bytes_le(), (Plus, vec![0, 2, 0, 0, 0, 0, 0, 0, 1]));
  82. }
  83. #[test]
  84. fn test_to_signed_bytes_le() {
  85. fn check(s: &str, result: Vec<u8>) {
  86. assert_eq!(
  87. BigInt::parse_bytes(s.as_bytes(), 10)
  88. .unwrap()
  89. .to_signed_bytes_le(),
  90. result
  91. );
  92. }
  93. check("0", vec![0]);
  94. check("32767", vec![0xff, 0x7f]);
  95. check("-1", vec![0xff]);
  96. check("16777216", vec![0, 0, 0, 1]);
  97. check("-100", vec![156]);
  98. check("-8388608", vec![0, 0, 0x80]);
  99. check("-192", vec![0x40, 0xff]);
  100. check("128", vec![0x80, 0])
  101. }
  102. #[test]
  103. fn test_from_signed_bytes_le() {
  104. fn check(s: &[u8], result: &str) {
  105. assert_eq!(
  106. BigInt::from_signed_bytes_le(s),
  107. BigInt::parse_bytes(result.as_bytes(), 10).unwrap()
  108. );
  109. }
  110. check(&[], "0");
  111. check(&[0], "0");
  112. check(&[0; 10], "0");
  113. check(&[0xff, 0x7f], "32767");
  114. check(&[0xff], "-1");
  115. check(&[0, 0, 0, 1], "16777216");
  116. check(&[156], "-100");
  117. check(&[0, 0, 0x80], "-8388608");
  118. check(&[0xff; 10], "-1");
  119. check(&[0x40, 0xff], "-192");
  120. }
  121. #[test]
  122. fn test_to_signed_bytes_be() {
  123. fn check(s: &str, result: Vec<u8>) {
  124. assert_eq!(
  125. BigInt::parse_bytes(s.as_bytes(), 10)
  126. .unwrap()
  127. .to_signed_bytes_be(),
  128. result
  129. );
  130. }
  131. check("0", vec![0]);
  132. check("32767", vec![0x7f, 0xff]);
  133. check("-1", vec![255]);
  134. check("16777216", vec![1, 0, 0, 0]);
  135. check("-100", vec![156]);
  136. check("-8388608", vec![128, 0, 0]);
  137. check("-192", vec![0xff, 0x40]);
  138. check("128", vec![0, 0x80]);
  139. }
  140. #[test]
  141. fn test_from_signed_bytes_be() {
  142. fn check(s: &[u8], result: &str) {
  143. assert_eq!(
  144. BigInt::from_signed_bytes_be(s),
  145. BigInt::parse_bytes(result.as_bytes(), 10).unwrap()
  146. );
  147. }
  148. check(&[], "0");
  149. check(&[0], "0");
  150. check(&[0; 10], "0");
  151. check(&[127, 255], "32767");
  152. check(&[255], "-1");
  153. check(&[1, 0, 0, 0], "16777216");
  154. check(&[156], "-100");
  155. check(&[128, 0, 0], "-8388608");
  156. check(&[255; 10], "-1");
  157. check(&[0xff, 0x40], "-192");
  158. }
  159. #[test]
  160. fn test_signed_bytes_be_round_trip() {
  161. for i in -0x1FFFF..0x20000 {
  162. let n = BigInt::from(i);
  163. assert_eq!(n, BigInt::from_signed_bytes_be(&n.to_signed_bytes_be()));
  164. }
  165. }
  166. #[test]
  167. fn test_signed_bytes_le_round_trip() {
  168. for i in -0x1FFFF..0x20000 {
  169. let n = BigInt::from(i);
  170. assert_eq!(n, BigInt::from_signed_bytes_le(&n.to_signed_bytes_le()));
  171. }
  172. }
  173. #[test]
  174. fn test_cmp() {
  175. let vs: [&[u32]; 4] = [&[2 as u32], &[1, 1], &[2, 1], &[1, 1, 1]];
  176. let mut nums = Vec::new();
  177. for s in vs.iter().rev() {
  178. nums.push(BigInt::from_slice(Minus, *s));
  179. }
  180. nums.push(Zero::zero());
  181. nums.extend(vs.iter().map(|s| BigInt::from_slice(Plus, *s)));
  182. for (i, ni) in nums.iter().enumerate() {
  183. for (j0, nj) in nums[i..].iter().enumerate() {
  184. let j = i + j0;
  185. if i == j {
  186. assert_eq!(ni.cmp(nj), Equal);
  187. assert_eq!(nj.cmp(ni), Equal);
  188. assert_eq!(ni, nj);
  189. assert!(!(ni != nj));
  190. assert!(ni <= nj);
  191. assert!(ni >= nj);
  192. assert!(!(ni < nj));
  193. assert!(!(ni > nj));
  194. } else {
  195. assert_eq!(ni.cmp(nj), Less);
  196. assert_eq!(nj.cmp(ni), Greater);
  197. assert!(!(ni == nj));
  198. assert!(ni != nj);
  199. assert!(ni <= nj);
  200. assert!(!(ni >= nj));
  201. assert!(ni < nj);
  202. assert!(!(ni > nj));
  203. assert!(!(nj <= ni));
  204. assert!(nj >= ni);
  205. assert!(!(nj < ni));
  206. assert!(nj > ni);
  207. }
  208. }
  209. }
  210. }
  211. fn hash<T: Hash>(x: &T) -> u64 {
  212. let mut hasher = <RandomState as BuildHasher>::Hasher::new();
  213. x.hash(&mut hasher);
  214. hasher.finish()
  215. }
  216. #[test]
  217. fn test_hash() {
  218. let a = BigInt::new(NoSign, vec![]);
  219. let b = BigInt::new(NoSign, vec![0]);
  220. let c = BigInt::new(Plus, vec![1]);
  221. let d = BigInt::new(Plus, vec![1, 0, 0, 0, 0, 0]);
  222. let e = BigInt::new(Plus, vec![0, 0, 0, 0, 0, 1]);
  223. let f = BigInt::new(Minus, vec![1]);
  224. assert!(hash(&a) == hash(&b));
  225. assert!(hash(&b) != hash(&c));
  226. assert!(hash(&c) == hash(&d));
  227. assert!(hash(&d) != hash(&e));
  228. assert!(hash(&c) != hash(&f));
  229. }
  230. #[test]
  231. fn test_convert_i64() {
  232. fn check(b1: BigInt, i: i64) {
  233. let b2: BigInt = FromPrimitive::from_i64(i).unwrap();
  234. assert!(b1 == b2);
  235. assert!(b1.to_i64().unwrap() == i);
  236. }
  237. check(Zero::zero(), 0);
  238. check(One::one(), 1);
  239. check(i64::MIN.to_bigint().unwrap(), i64::MIN);
  240. check(i64::MAX.to_bigint().unwrap(), i64::MAX);
  241. assert_eq!((i64::MAX as u64 + 1).to_bigint().unwrap().to_i64(), None);
  242. assert_eq!(
  243. BigInt::from_biguint(Plus, BigUint::new(vec![1, 2, 3, 4, 5])).to_i64(),
  244. None
  245. );
  246. assert_eq!(
  247. BigInt::from_biguint(Minus, BigUint::new(vec![1, 0, 0, 1 << 31])).to_i64(),
  248. None
  249. );
  250. assert_eq!(
  251. BigInt::from_biguint(Minus, BigUint::new(vec![1, 2, 3, 4, 5])).to_i64(),
  252. None
  253. );
  254. }
  255. #[test]
  256. fn test_convert_i128() {
  257. fn check(b1: BigInt, i: i128) {
  258. let b2: BigInt = FromPrimitive::from_i128(i).unwrap();
  259. assert!(b1 == b2);
  260. assert!(b1.to_i128().unwrap() == i);
  261. }
  262. check(Zero::zero(), 0);
  263. check(One::one(), 1);
  264. check(i128::MIN.to_bigint().unwrap(), i128::MIN);
  265. check(i128::MAX.to_bigint().unwrap(), i128::MAX);
  266. assert_eq!((i128::MAX as u128 + 1).to_bigint().unwrap().to_i128(), None);
  267. assert_eq!(
  268. BigInt::from_biguint(Plus, BigUint::new(vec![1, 2, 3, 4, 5])).to_i128(),
  269. None
  270. );
  271. assert_eq!(
  272. BigInt::from_biguint(Minus, BigUint::new(vec![1, 0, 0, 1 << 31])).to_i128(),
  273. None
  274. );
  275. assert_eq!(
  276. BigInt::from_biguint(Minus, BigUint::new(vec![1, 2, 3, 4, 5])).to_i128(),
  277. None
  278. );
  279. }
  280. #[test]
  281. fn test_convert_u64() {
  282. fn check(b1: BigInt, u: u64) {
  283. let b2: BigInt = FromPrimitive::from_u64(u).unwrap();
  284. assert!(b1 == b2);
  285. assert!(b1.to_u64().unwrap() == u);
  286. }
  287. check(Zero::zero(), 0);
  288. check(One::one(), 1);
  289. check(u64::MIN.to_bigint().unwrap(), u64::MIN);
  290. check(u64::MAX.to_bigint().unwrap(), u64::MAX);
  291. assert_eq!(
  292. BigInt::from_biguint(Plus, BigUint::new(vec![1, 2, 3, 4, 5])).to_u64(),
  293. None
  294. );
  295. let max_value: BigUint = FromPrimitive::from_u64(u64::MAX).unwrap();
  296. assert_eq!(BigInt::from_biguint(Minus, max_value).to_u64(), None);
  297. assert_eq!(
  298. BigInt::from_biguint(Minus, BigUint::new(vec![1, 2, 3, 4, 5])).to_u64(),
  299. None
  300. );
  301. }
  302. #[test]
  303. fn test_convert_u128() {
  304. fn check(b1: BigInt, u: u128) {
  305. let b2: BigInt = FromPrimitive::from_u128(u).unwrap();
  306. assert!(b1 == b2);
  307. assert!(b1.to_u128().unwrap() == u);
  308. }
  309. check(Zero::zero(), 0);
  310. check(One::one(), 1);
  311. check(u128::MIN.to_bigint().unwrap(), u128::MIN);
  312. check(u128::MAX.to_bigint().unwrap(), u128::MAX);
  313. assert_eq!(
  314. BigInt::from_biguint(Plus, BigUint::new(vec![1, 2, 3, 4, 5])).to_u128(),
  315. None
  316. );
  317. let max_value: BigUint = FromPrimitive::from_u128(u128::MAX).unwrap();
  318. assert_eq!(BigInt::from_biguint(Minus, max_value).to_u128(), None);
  319. assert_eq!(
  320. BigInt::from_biguint(Minus, BigUint::new(vec![1, 2, 3, 4, 5])).to_u128(),
  321. None
  322. );
  323. }
  324. #[test]
  325. #[allow(clippy::float_cmp)]
  326. fn test_convert_f32() {
  327. fn check(b1: &BigInt, f: f32) {
  328. let b2 = BigInt::from_f32(f).unwrap();
  329. assert_eq!(b1, &b2);
  330. assert_eq!(b1.to_f32().unwrap(), f);
  331. let neg_b1 = -b1;
  332. let neg_b2 = BigInt::from_f32(-f).unwrap();
  333. assert_eq!(neg_b1, neg_b2);
  334. assert_eq!(neg_b1.to_f32().unwrap(), -f);
  335. }
  336. check(&BigInt::zero(), 0.0);
  337. check(&BigInt::one(), 1.0);
  338. check(&BigInt::from(u16::MAX), pow(2.0_f32, 16) - 1.0);
  339. check(&BigInt::from(1u64 << 32), pow(2.0_f32, 32));
  340. check(&BigInt::from_slice(Plus, &[0, 0, 1]), pow(2.0_f32, 64));
  341. check(
  342. &((BigInt::one() << 100) + (BigInt::one() << 123)),
  343. pow(2.0_f32, 100) + pow(2.0_f32, 123),
  344. );
  345. check(&(BigInt::one() << 127), pow(2.0_f32, 127));
  346. check(&(BigInt::from((1u64 << 24) - 1) << (128 - 24)), f32::MAX);
  347. // keeping all 24 digits with the bits at different offsets to the BigDigits
  348. let x: u32 = 0b00000000101111011111011011011101;
  349. let mut f = x as f32;
  350. let mut b = BigInt::from(x);
  351. for _ in 0..64 {
  352. check(&b, f);
  353. f *= 2.0;
  354. b <<= 1;
  355. }
  356. // this number when rounded to f64 then f32 isn't the same as when rounded straight to f32
  357. let mut n: i64 = 0b0000000000111111111111111111111111011111111111111111111111111111;
  358. assert!((n as f64) as f32 != n as f32);
  359. assert_eq!(BigInt::from(n).to_f32(), Some(n as f32));
  360. n = -n;
  361. assert!((n as f64) as f32 != n as f32);
  362. assert_eq!(BigInt::from(n).to_f32(), Some(n as f32));
  363. // test rounding up with the bits at different offsets to the BigDigits
  364. let mut f = ((1u64 << 25) - 1) as f32;
  365. let mut b = BigInt::from(1u64 << 25);
  366. for _ in 0..64 {
  367. assert_eq!(b.to_f32(), Some(f));
  368. f *= 2.0;
  369. b <<= 1;
  370. }
  371. // rounding
  372. assert_eq!(
  373. BigInt::from_f32(-f32::consts::PI),
  374. Some(BigInt::from(-3i32))
  375. );
  376. assert_eq!(BigInt::from_f32(-f32::consts::E), Some(BigInt::from(-2i32)));
  377. assert_eq!(BigInt::from_f32(-0.99999), Some(BigInt::zero()));
  378. assert_eq!(BigInt::from_f32(-0.5), Some(BigInt::zero()));
  379. assert_eq!(BigInt::from_f32(-0.0), Some(BigInt::zero()));
  380. assert_eq!(
  381. BigInt::from_f32(f32::MIN_POSITIVE / 2.0),
  382. Some(BigInt::zero())
  383. );
  384. assert_eq!(BigInt::from_f32(f32::MIN_POSITIVE), Some(BigInt::zero()));
  385. assert_eq!(BigInt::from_f32(0.5), Some(BigInt::zero()));
  386. assert_eq!(BigInt::from_f32(0.99999), Some(BigInt::zero()));
  387. assert_eq!(BigInt::from_f32(f32::consts::E), Some(BigInt::from(2u32)));
  388. assert_eq!(BigInt::from_f32(f32::consts::PI), Some(BigInt::from(3u32)));
  389. // special float values
  390. assert_eq!(BigInt::from_f32(f32::NAN), None);
  391. assert_eq!(BigInt::from_f32(f32::INFINITY), None);
  392. assert_eq!(BigInt::from_f32(f32::NEG_INFINITY), None);
  393. // largest BigInt that will round to a finite f32 value
  394. let big_num = (BigInt::one() << 128u8) - 1u8 - (BigInt::one() << (128u8 - 25));
  395. assert_eq!(big_num.to_f32(), Some(f32::MAX));
  396. assert_eq!((&big_num + 1u8).to_f32(), Some(f32::INFINITY));
  397. assert_eq!((-&big_num).to_f32(), Some(f32::MIN));
  398. assert_eq!(((-&big_num) - 1u8).to_f32(), Some(f32::NEG_INFINITY));
  399. assert_eq!(
  400. ((BigInt::one() << 128u8) - 1u8).to_f32(),
  401. Some(f32::INFINITY)
  402. );
  403. assert_eq!((BigInt::one() << 128u8).to_f32(), Some(f32::INFINITY));
  404. assert_eq!(
  405. (-((BigInt::one() << 128u8) - 1u8)).to_f32(),
  406. Some(f32::NEG_INFINITY)
  407. );
  408. assert_eq!(
  409. (-(BigInt::one() << 128u8)).to_f32(),
  410. Some(f32::NEG_INFINITY)
  411. );
  412. }
  413. #[test]
  414. #[allow(clippy::float_cmp)]
  415. fn test_convert_f64() {
  416. fn check(b1: &BigInt, f: f64) {
  417. let b2 = BigInt::from_f64(f).unwrap();
  418. assert_eq!(b1, &b2);
  419. assert_eq!(b1.to_f64().unwrap(), f);
  420. let neg_b1 = -b1;
  421. let neg_b2 = BigInt::from_f64(-f).unwrap();
  422. assert_eq!(neg_b1, neg_b2);
  423. assert_eq!(neg_b1.to_f64().unwrap(), -f);
  424. }
  425. check(&BigInt::zero(), 0.0);
  426. check(&BigInt::one(), 1.0);
  427. check(&BigInt::from(u32::MAX), pow(2.0_f64, 32) - 1.0);
  428. check(&BigInt::from(1u64 << 32), pow(2.0_f64, 32));
  429. check(&BigInt::from_slice(Plus, &[0, 0, 1]), pow(2.0_f64, 64));
  430. check(
  431. &((BigInt::one() << 100) + (BigInt::one() << 152)),
  432. pow(2.0_f64, 100) + pow(2.0_f64, 152),
  433. );
  434. check(&(BigInt::one() << 1023), pow(2.0_f64, 1023));
  435. check(&(BigInt::from((1u64 << 53) - 1) << (1024 - 53)), f64::MAX);
  436. // keeping all 53 digits with the bits at different offsets to the BigDigits
  437. let x: u64 = 0b0000000000011110111110110111111101110111101111011111011011011101;
  438. let mut f = x as f64;
  439. let mut b = BigInt::from(x);
  440. for _ in 0..128 {
  441. check(&b, f);
  442. f *= 2.0;
  443. b <<= 1;
  444. }
  445. // test rounding up with the bits at different offsets to the BigDigits
  446. let mut f = ((1u64 << 54) - 1) as f64;
  447. let mut b = BigInt::from(1u64 << 54);
  448. for _ in 0..128 {
  449. assert_eq!(b.to_f64(), Some(f));
  450. f *= 2.0;
  451. b <<= 1;
  452. }
  453. // rounding
  454. assert_eq!(
  455. BigInt::from_f64(-f64::consts::PI),
  456. Some(BigInt::from(-3i32))
  457. );
  458. assert_eq!(BigInt::from_f64(-f64::consts::E), Some(BigInt::from(-2i32)));
  459. assert_eq!(BigInt::from_f64(-0.99999), Some(BigInt::zero()));
  460. assert_eq!(BigInt::from_f64(-0.5), Some(BigInt::zero()));
  461. assert_eq!(BigInt::from_f64(-0.0), Some(BigInt::zero()));
  462. assert_eq!(
  463. BigInt::from_f64(f64::MIN_POSITIVE / 2.0),
  464. Some(BigInt::zero())
  465. );
  466. assert_eq!(BigInt::from_f64(f64::MIN_POSITIVE), Some(BigInt::zero()));
  467. assert_eq!(BigInt::from_f64(0.5), Some(BigInt::zero()));
  468. assert_eq!(BigInt::from_f64(0.99999), Some(BigInt::zero()));
  469. assert_eq!(BigInt::from_f64(f64::consts::E), Some(BigInt::from(2u32)));
  470. assert_eq!(BigInt::from_f64(f64::consts::PI), Some(BigInt::from(3u32)));
  471. // special float values
  472. assert_eq!(BigInt::from_f64(f64::NAN), None);
  473. assert_eq!(BigInt::from_f64(f64::INFINITY), None);
  474. assert_eq!(BigInt::from_f64(f64::NEG_INFINITY), None);
  475. // largest BigInt that will round to a finite f64 value
  476. let big_num = (BigInt::one() << 1024u16) - 1u8 - (BigInt::one() << (1024u16 - 54));
  477. assert_eq!(big_num.to_f64(), Some(f64::MAX));
  478. assert_eq!((&big_num + 1u8).to_f64(), Some(f64::INFINITY));
  479. assert_eq!((-&big_num).to_f64(), Some(f64::MIN));
  480. assert_eq!(((-&big_num) - 1u8).to_f64(), Some(f64::NEG_INFINITY));
  481. assert_eq!(
  482. ((BigInt::one() << 1024u16) - 1u8).to_f64(),
  483. Some(f64::INFINITY)
  484. );
  485. assert_eq!((BigInt::one() << 1024u16).to_f64(), Some(f64::INFINITY));
  486. assert_eq!(
  487. (-((BigInt::one() << 1024u16) - 1u8)).to_f64(),
  488. Some(f64::NEG_INFINITY)
  489. );
  490. assert_eq!(
  491. (-(BigInt::one() << 1024u16)).to_f64(),
  492. Some(f64::NEG_INFINITY)
  493. );
  494. }
  495. #[test]
  496. fn test_convert_to_biguint() {
  497. fn check(n: BigInt, ans_1: BigUint) {
  498. assert_eq!(n.to_biguint().unwrap(), ans_1);
  499. assert_eq!(n.to_biguint().unwrap().to_bigint().unwrap(), n);
  500. }
  501. let zero: BigInt = Zero::zero();
  502. let unsigned_zero: BigUint = Zero::zero();
  503. let positive = BigInt::from_biguint(Plus, BigUint::new(vec![1, 2, 3]));
  504. let negative = -&positive;
  505. check(zero, unsigned_zero);
  506. check(positive, BigUint::new(vec![1, 2, 3]));
  507. assert_eq!(negative.to_biguint(), None);
  508. }
  509. #[test]
  510. fn test_convert_from_uint() {
  511. macro_rules! check {
  512. ($ty:ident, $max:expr) => {
  513. assert_eq!(BigInt::from($ty::zero()), BigInt::zero());
  514. assert_eq!(BigInt::from($ty::one()), BigInt::one());
  515. assert_eq!(BigInt::from($ty::MAX - $ty::one()), $max - BigInt::one());
  516. assert_eq!(BigInt::from($ty::MAX), $max);
  517. };
  518. }
  519. check!(u8, BigInt::from_slice(Plus, &[u8::MAX as u32]));
  520. check!(u16, BigInt::from_slice(Plus, &[u16::MAX as u32]));
  521. check!(u32, BigInt::from_slice(Plus, &[u32::MAX]));
  522. check!(u64, BigInt::from_slice(Plus, &[u32::MAX, u32::MAX]));
  523. check!(
  524. u128,
  525. BigInt::from_slice(Plus, &[u32::MAX, u32::MAX, u32::MAX, u32::MAX])
  526. );
  527. check!(usize, BigInt::from(usize::MAX as u64));
  528. }
  529. #[test]
  530. fn test_convert_from_int() {
  531. macro_rules! check {
  532. ($ty:ident, $min:expr, $max:expr) => {
  533. assert_eq!(BigInt::from($ty::MIN), $min);
  534. assert_eq!(BigInt::from($ty::MIN + $ty::one()), $min + BigInt::one());
  535. assert_eq!(BigInt::from(-$ty::one()), -BigInt::one());
  536. assert_eq!(BigInt::from($ty::zero()), BigInt::zero());
  537. assert_eq!(BigInt::from($ty::one()), BigInt::one());
  538. assert_eq!(BigInt::from($ty::MAX - $ty::one()), $max - BigInt::one());
  539. assert_eq!(BigInt::from($ty::MAX), $max);
  540. };
  541. }
  542. check!(
  543. i8,
  544. BigInt::from_slice(Minus, &[1 << 7]),
  545. BigInt::from_slice(Plus, &[i8::MAX as u32])
  546. );
  547. check!(
  548. i16,
  549. BigInt::from_slice(Minus, &[1 << 15]),
  550. BigInt::from_slice(Plus, &[i16::MAX as u32])
  551. );
  552. check!(
  553. i32,
  554. BigInt::from_slice(Minus, &[1 << 31]),
  555. BigInt::from_slice(Plus, &[i32::MAX as u32])
  556. );
  557. check!(
  558. i64,
  559. BigInt::from_slice(Minus, &[0, 1 << 31]),
  560. BigInt::from_slice(Plus, &[u32::MAX, i32::MAX as u32])
  561. );
  562. check!(
  563. i128,
  564. BigInt::from_slice(Minus, &[0, 0, 0, 1 << 31]),
  565. BigInt::from_slice(Plus, &[u32::MAX, u32::MAX, u32::MAX, i32::MAX as u32])
  566. );
  567. check!(
  568. isize,
  569. BigInt::from(isize::MIN as i64),
  570. BigInt::from(isize::MAX as i64)
  571. );
  572. }
  573. #[test]
  574. fn test_convert_from_biguint() {
  575. assert_eq!(BigInt::from(BigUint::zero()), BigInt::zero());
  576. assert_eq!(BigInt::from(BigUint::one()), BigInt::one());
  577. assert_eq!(
  578. BigInt::from(BigUint::from_slice(&[1, 2, 3])),
  579. BigInt::from_slice(Plus, &[1, 2, 3])
  580. );
  581. }
  582. #[test]
  583. fn test_add() {
  584. for elm in SUM_TRIPLES.iter() {
  585. let (a_vec, b_vec, c_vec) = *elm;
  586. let a = BigInt::from_slice(Plus, a_vec);
  587. let b = BigInt::from_slice(Plus, b_vec);
  588. let c = BigInt::from_slice(Plus, c_vec);
  589. let (na, nb, nc) = (-&a, -&b, -&c);
  590. assert_op!(a + b == c);
  591. assert_op!(b + a == c);
  592. assert_op!(c + na == b);
  593. assert_op!(c + nb == a);
  594. assert_op!(a + nc == nb);
  595. assert_op!(b + nc == na);
  596. assert_op!(na + nb == nc);
  597. assert_op!(a + na == BigInt::zero());
  598. assert_assign_op!(a += b == c);
  599. assert_assign_op!(b += a == c);
  600. assert_assign_op!(c += na == b);
  601. assert_assign_op!(c += nb == a);
  602. assert_assign_op!(a += nc == nb);
  603. assert_assign_op!(b += nc == na);
  604. assert_assign_op!(na += nb == nc);
  605. assert_assign_op!(a += na == BigInt::zero());
  606. }
  607. }
  608. #[test]
  609. fn test_sub() {
  610. for elm in SUM_TRIPLES.iter() {
  611. let (a_vec, b_vec, c_vec) = *elm;
  612. let a = BigInt::from_slice(Plus, a_vec);
  613. let b = BigInt::from_slice(Plus, b_vec);
  614. let c = BigInt::from_slice(Plus, c_vec);
  615. let (na, nb, nc) = (-&a, -&b, -&c);
  616. assert_op!(c - a == b);
  617. assert_op!(c - b == a);
  618. assert_op!(nb - a == nc);
  619. assert_op!(na - b == nc);
  620. assert_op!(b - na == c);
  621. assert_op!(a - nb == c);
  622. assert_op!(nc - na == nb);
  623. assert_op!(a - a == BigInt::zero());
  624. assert_assign_op!(c -= a == b);
  625. assert_assign_op!(c -= b == a);
  626. assert_assign_op!(nb -= a == nc);
  627. assert_assign_op!(na -= b == nc);
  628. assert_assign_op!(b -= na == c);
  629. assert_assign_op!(a -= nb == c);
  630. assert_assign_op!(nc -= na == nb);
  631. assert_assign_op!(a -= a == BigInt::zero());
  632. }
  633. }
  634. #[test]
  635. fn test_mul() {
  636. for elm in MUL_TRIPLES.iter() {
  637. let (a_vec, b_vec, c_vec) = *elm;
  638. let a = BigInt::from_slice(Plus, a_vec);
  639. let b = BigInt::from_slice(Plus, b_vec);
  640. let c = BigInt::from_slice(Plus, c_vec);
  641. let (na, nb, nc) = (-&a, -&b, -&c);
  642. assert_op!(a * b == c);
  643. assert_op!(b * a == c);
  644. assert_op!(na * nb == c);
  645. assert_op!(na * b == nc);
  646. assert_op!(nb * a == nc);
  647. assert_assign_op!(a *= b == c);
  648. assert_assign_op!(b *= a == c);
  649. assert_assign_op!(na *= nb == c);
  650. assert_assign_op!(na *= b == nc);
  651. assert_assign_op!(nb *= a == nc);
  652. }
  653. for elm in DIV_REM_QUADRUPLES.iter() {
  654. let (a_vec, b_vec, c_vec, d_vec) = *elm;
  655. let a = BigInt::from_slice(Plus, a_vec);
  656. let b = BigInt::from_slice(Plus, b_vec);
  657. let c = BigInt::from_slice(Plus, c_vec);
  658. let d = BigInt::from_slice(Plus, d_vec);
  659. assert!(a == &b * &c + &d);
  660. assert!(a == &c * &b + &d);
  661. }
  662. }
  663. #[test]
  664. fn test_div_mod_floor() {
  665. fn check_sub(a: &BigInt, b: &BigInt, ans_d: &BigInt, ans_m: &BigInt) {
  666. let (d, m) = a.div_mod_floor(b);
  667. assert_eq!(d, a.div_floor(b));
  668. assert_eq!(m, a.mod_floor(b));
  669. if !m.is_zero() {
  670. assert_eq!(m.sign(), b.sign());
  671. }
  672. assert!(m.abs() <= b.abs());
  673. assert!(*a == b * &d + &m);
  674. assert!(d == *ans_d);
  675. assert!(m == *ans_m);
  676. }
  677. fn check(a: &BigInt, b: &BigInt, d: &BigInt, m: &BigInt) {
  678. if m.is_zero() {
  679. check_sub(a, b, d, m);
  680. check_sub(a, &b.neg(), &d.neg(), m);
  681. check_sub(&a.neg(), b, &d.neg(), m);
  682. check_sub(&a.neg(), &b.neg(), d, m);
  683. } else {
  684. let one: BigInt = One::one();
  685. check_sub(a, b, d, m);
  686. check_sub(a, &b.neg(), &(d.neg() - &one), &(m - b));
  687. check_sub(&a.neg(), b, &(d.neg() - &one), &(b - m));
  688. check_sub(&a.neg(), &b.neg(), d, &m.neg());
  689. }
  690. }
  691. for elm in MUL_TRIPLES.iter() {
  692. let (a_vec, b_vec, c_vec) = *elm;
  693. let a = BigInt::from_slice(Plus, a_vec);
  694. let b = BigInt::from_slice(Plus, b_vec);
  695. let c = BigInt::from_slice(Plus, c_vec);
  696. if !a.is_zero() {
  697. check(&c, &a, &b, &Zero::zero());
  698. }
  699. if !b.is_zero() {
  700. check(&c, &b, &a, &Zero::zero());
  701. }
  702. }
  703. for elm in DIV_REM_QUADRUPLES.iter() {
  704. let (a_vec, b_vec, c_vec, d_vec) = *elm;
  705. let a = BigInt::from_slice(Plus, a_vec);
  706. let b = BigInt::from_slice(Plus, b_vec);
  707. let c = BigInt::from_slice(Plus, c_vec);
  708. let d = BigInt::from_slice(Plus, d_vec);
  709. if !b.is_zero() {
  710. check(&a, &b, &c, &d);
  711. }
  712. }
  713. }
  714. #[test]
  715. fn test_div_rem() {
  716. fn check_sub(a: &BigInt, b: &BigInt, ans_q: &BigInt, ans_r: &BigInt) {
  717. let (q, r) = a.div_rem(b);
  718. if !r.is_zero() {
  719. assert_eq!(r.sign(), a.sign());
  720. }
  721. assert!(r.abs() <= b.abs());
  722. assert!(*a == b * &q + &r);
  723. assert!(q == *ans_q);
  724. assert!(r == *ans_r);
  725. let (a, b, ans_q, ans_r) = (a.clone(), b.clone(), ans_q.clone(), ans_r.clone());
  726. assert_op!(a / b == ans_q);
  727. assert_op!(a % b == ans_r);
  728. assert_assign_op!(a /= b == ans_q);
  729. assert_assign_op!(a %= b == ans_r);
  730. }
  731. fn check(a: &BigInt, b: &BigInt, q: &BigInt, r: &BigInt) {
  732. check_sub(a, b, q, r);
  733. check_sub(a, &b.neg(), &q.neg(), r);
  734. check_sub(&a.neg(), b, &q.neg(), &r.neg());
  735. check_sub(&a.neg(), &b.neg(), q, &r.neg());
  736. }
  737. for elm in MUL_TRIPLES.iter() {
  738. let (a_vec, b_vec, c_vec) = *elm;
  739. let a = BigInt::from_slice(Plus, a_vec);
  740. let b = BigInt::from_slice(Plus, b_vec);
  741. let c = BigInt::from_slice(Plus, c_vec);
  742. if !a.is_zero() {
  743. check(&c, &a, &b, &Zero::zero());
  744. }
  745. if !b.is_zero() {
  746. check(&c, &b, &a, &Zero::zero());
  747. }
  748. }
  749. for elm in DIV_REM_QUADRUPLES.iter() {
  750. let (a_vec, b_vec, c_vec, d_vec) = *elm;
  751. let a = BigInt::from_slice(Plus, a_vec);
  752. let b = BigInt::from_slice(Plus, b_vec);
  753. let c = BigInt::from_slice(Plus, c_vec);
  754. let d = BigInt::from_slice(Plus, d_vec);
  755. if !b.is_zero() {
  756. check(&a, &b, &c, &d);
  757. }
  758. }
  759. }
  760. #[test]
  761. fn test_div_ceil() {
  762. fn check_sub(a: &BigInt, b: &BigInt, ans_d: &BigInt) {
  763. assert_eq!(a.div_ceil(b), *ans_d);
  764. }
  765. fn check(a: &BigInt, b: &BigInt, d: &BigInt, m: &BigInt) {
  766. if m.is_zero() {
  767. check_sub(a, b, d);
  768. check_sub(a, &b.neg(), &d.neg());
  769. check_sub(&a.neg(), b, &d.neg());
  770. check_sub(&a.neg(), &b.neg(), d);
  771. } else {
  772. check_sub(a, b, &(d + 1));
  773. check_sub(a, &b.neg(), &d.neg());
  774. check_sub(&a.neg(), b, &d.neg());
  775. check_sub(&a.neg(), &b.neg(), &(d + 1));
  776. }
  777. }
  778. for elm in MUL_TRIPLES.iter() {
  779. let (a_vec, b_vec, c_vec) = *elm;
  780. let a = BigInt::from_slice(Plus, a_vec);
  781. let b = BigInt::from_slice(Plus, b_vec);
  782. let c = BigInt::from_slice(Plus, c_vec);
  783. if !a.is_zero() {
  784. check(&c, &a, &b, &Zero::zero());
  785. }
  786. if !b.is_zero() {
  787. check(&c, &b, &a, &Zero::zero());
  788. }
  789. }
  790. for elm in DIV_REM_QUADRUPLES.iter() {
  791. let (a_vec, b_vec, c_vec, d_vec) = *elm;
  792. let a = BigInt::from_slice(Plus, a_vec);
  793. let b = BigInt::from_slice(Plus, b_vec);
  794. let c = BigInt::from_slice(Plus, c_vec);
  795. let d = BigInt::from_slice(Plus, d_vec);
  796. if !b.is_zero() {
  797. check(&a, &b, &c, &d);
  798. }
  799. }
  800. }
  801. #[test]
  802. fn test_checked_add() {
  803. for elm in SUM_TRIPLES.iter() {
  804. let (a_vec, b_vec, c_vec) = *elm;
  805. let a = BigInt::from_slice(Plus, a_vec);
  806. let b = BigInt::from_slice(Plus, b_vec);
  807. let c = BigInt::from_slice(Plus, c_vec);
  808. assert!(a.checked_add(&b).unwrap() == c);
  809. assert!(b.checked_add(&a).unwrap() == c);
  810. assert!(c.checked_add(&(-&a)).unwrap() == b);
  811. assert!(c.checked_add(&(-&b)).unwrap() == a);
  812. assert!(a.checked_add(&(-&c)).unwrap() == (-&b));
  813. assert!(b.checked_add(&(-&c)).unwrap() == (-&a));
  814. assert!((-&a).checked_add(&(-&b)).unwrap() == (-&c));
  815. assert!(a.checked_add(&(-&a)).unwrap() == BigInt::zero());
  816. }
  817. }
  818. #[test]
  819. fn test_checked_sub() {
  820. for elm in SUM_TRIPLES.iter() {
  821. let (a_vec, b_vec, c_vec) = *elm;
  822. let a = BigInt::from_slice(Plus, a_vec);
  823. let b = BigInt::from_slice(Plus, b_vec);
  824. let c = BigInt::from_slice(Plus, c_vec);
  825. assert!(c.checked_sub(&a).unwrap() == b);
  826. assert!(c.checked_sub(&b).unwrap() == a);
  827. assert!((-&b).checked_sub(&a).unwrap() == (-&c));
  828. assert!((-&a).checked_sub(&b).unwrap() == (-&c));
  829. assert!(b.checked_sub(&(-&a)).unwrap() == c);
  830. assert!(a.checked_sub(&(-&b)).unwrap() == c);
  831. assert!((-&c).checked_sub(&(-&a)).unwrap() == (-&b));
  832. assert!(a.checked_sub(&a).unwrap() == BigInt::zero());
  833. }
  834. }
  835. #[test]
  836. fn test_checked_mul() {
  837. for elm in MUL_TRIPLES.iter() {
  838. let (a_vec, b_vec, c_vec) = *elm;
  839. let a = BigInt::from_slice(Plus, a_vec);
  840. let b = BigInt::from_slice(Plus, b_vec);
  841. let c = BigInt::from_slice(Plus, c_vec);
  842. assert!(a.checked_mul(&b).unwrap() == c);
  843. assert!(b.checked_mul(&a).unwrap() == c);
  844. assert!((-&a).checked_mul(&b).unwrap() == -&c);
  845. assert!((-&b).checked_mul(&a).unwrap() == -&c);
  846. }
  847. for elm in DIV_REM_QUADRUPLES.iter() {
  848. let (a_vec, b_vec, c_vec, d_vec) = *elm;
  849. let a = BigInt::from_slice(Plus, a_vec);
  850. let b = BigInt::from_slice(Plus, b_vec);
  851. let c = BigInt::from_slice(Plus, c_vec);
  852. let d = BigInt::from_slice(Plus, d_vec);
  853. assert!(a == b.checked_mul(&c).unwrap() + &d);
  854. assert!(a == c.checked_mul(&b).unwrap() + &d);
  855. }
  856. }
  857. #[test]
  858. fn test_checked_div() {
  859. for elm in MUL_TRIPLES.iter() {
  860. let (a_vec, b_vec, c_vec) = *elm;
  861. let a = BigInt::from_slice(Plus, a_vec);
  862. let b = BigInt::from_slice(Plus, b_vec);
  863. let c = BigInt::from_slice(Plus, c_vec);
  864. if !a.is_zero() {
  865. assert!(c.checked_div(&a).unwrap() == b);
  866. assert!((-&c).checked_div(&(-&a)).unwrap() == b);
  867. assert!((-&c).checked_div(&a).unwrap() == -&b);
  868. }
  869. if !b.is_zero() {
  870. assert!(c.checked_div(&b).unwrap() == a);
  871. assert!((-&c).checked_div(&(-&b)).unwrap() == a);
  872. assert!((-&c).checked_div(&b).unwrap() == -&a);
  873. }
  874. assert!(c.checked_div(&Zero::zero()).is_none());
  875. assert!((-&c).checked_div(&Zero::zero()).is_none());
  876. }
  877. }
  878. #[test]
  879. fn test_gcd() {
  880. fn check(a: isize, b: isize, c: isize) {
  881. let big_a: BigInt = FromPrimitive::from_isize(a).unwrap();
  882. let big_b: BigInt = FromPrimitive::from_isize(b).unwrap();
  883. let big_c: BigInt = FromPrimitive::from_isize(c).unwrap();
  884. assert_eq!(big_a.gcd(&big_b), big_c);
  885. assert_eq!(big_a.extended_gcd(&big_b).gcd, big_c);
  886. assert_eq!(big_a.gcd_lcm(&big_b).0, big_c);
  887. assert_eq!(big_a.extended_gcd_lcm(&big_b).0.gcd, big_c);
  888. }
  889. check(10, 2, 2);
  890. check(10, 3, 1);
  891. check(0, 3, 3);
  892. check(3, 3, 3);
  893. check(56, 42, 14);
  894. check(3, -3, 3);
  895. check(-6, 3, 3);
  896. check(-4, -2, 2);
  897. }
  898. #[test]
  899. fn test_lcm() {
  900. fn check(a: isize, b: isize, c: isize) {
  901. let big_a: BigInt = FromPrimitive::from_isize(a).unwrap();
  902. let big_b: BigInt = FromPrimitive::from_isize(b).unwrap();
  903. let big_c: BigInt = FromPrimitive::from_isize(c).unwrap();
  904. assert_eq!(big_a.lcm(&big_b), big_c);
  905. assert_eq!(big_a.gcd_lcm(&big_b).1, big_c);
  906. assert_eq!(big_a.extended_gcd_lcm(&big_b).1, big_c);
  907. }
  908. check(0, 0, 0);
  909. check(1, 0, 0);
  910. check(0, 1, 0);
  911. check(1, 1, 1);
  912. check(-1, 1, 1);
  913. check(1, -1, 1);
  914. check(-1, -1, 1);
  915. check(8, 9, 72);
  916. check(11, 5, 55);
  917. }
  918. #[test]
  919. fn test_next_multiple_of() {
  920. assert_eq!(
  921. BigInt::from(16).next_multiple_of(&BigInt::from(8)),
  922. BigInt::from(16)
  923. );
  924. assert_eq!(
  925. BigInt::from(23).next_multiple_of(&BigInt::from(8)),
  926. BigInt::from(24)
  927. );
  928. assert_eq!(
  929. BigInt::from(16).next_multiple_of(&BigInt::from(-8)),
  930. BigInt::from(16)
  931. );
  932. assert_eq!(
  933. BigInt::from(23).next_multiple_of(&BigInt::from(-8)),
  934. BigInt::from(16)
  935. );
  936. assert_eq!(
  937. BigInt::from(-16).next_multiple_of(&BigInt::from(8)),
  938. BigInt::from(-16)
  939. );
  940. assert_eq!(
  941. BigInt::from(-23).next_multiple_of(&BigInt::from(8)),
  942. BigInt::from(-16)
  943. );
  944. assert_eq!(
  945. BigInt::from(-16).next_multiple_of(&BigInt::from(-8)),
  946. BigInt::from(-16)
  947. );
  948. assert_eq!(
  949. BigInt::from(-23).next_multiple_of(&BigInt::from(-8)),
  950. BigInt::from(-24)
  951. );
  952. }
  953. #[test]
  954. fn test_prev_multiple_of() {
  955. assert_eq!(
  956. BigInt::from(16).prev_multiple_of(&BigInt::from(8)),
  957. BigInt::from(16)
  958. );
  959. assert_eq!(
  960. BigInt::from(23).prev_multiple_of(&BigInt::from(8)),
  961. BigInt::from(16)
  962. );
  963. assert_eq!(
  964. BigInt::from(16).prev_multiple_of(&BigInt::from(-8)),
  965. BigInt::from(16)
  966. );
  967. assert_eq!(
  968. BigInt::from(23).prev_multiple_of(&BigInt::from(-8)),
  969. BigInt::from(24)
  970. );
  971. assert_eq!(
  972. BigInt::from(-16).prev_multiple_of(&BigInt::from(8)),
  973. BigInt::from(-16)
  974. );
  975. assert_eq!(
  976. BigInt::from(-23).prev_multiple_of(&BigInt::from(8)),
  977. BigInt::from(-24)
  978. );
  979. assert_eq!(
  980. BigInt::from(-16).prev_multiple_of(&BigInt::from(-8)),
  981. BigInt::from(-16)
  982. );
  983. assert_eq!(
  984. BigInt::from(-23).prev_multiple_of(&BigInt::from(-8)),
  985. BigInt::from(-16)
  986. );
  987. }
  988. #[test]
  989. fn test_abs_sub() {
  990. let zero: BigInt = Zero::zero();
  991. let one: BigInt = One::one();
  992. assert_eq!((-&one).abs_sub(&one), zero);
  993. let one: BigInt = One::one();
  994. let zero: BigInt = Zero::zero();
  995. assert_eq!(one.abs_sub(&one), zero);
  996. let one: BigInt = One::one();
  997. let zero: BigInt = Zero::zero();
  998. assert_eq!(one.abs_sub(&zero), one);
  999. let one: BigInt = One::one();
  1000. let two: BigInt = FromPrimitive::from_isize(2).unwrap();
  1001. assert_eq!(one.abs_sub(&-&one), two);
  1002. }
  1003. #[test]
  1004. fn test_from_str_radix() {
  1005. fn check(s: &str, ans: Option<isize>) {
  1006. let ans = ans.map(|n| {
  1007. let x: BigInt = FromPrimitive::from_isize(n).unwrap();
  1008. x
  1009. });
  1010. assert_eq!(BigInt::from_str_radix(s, 10).ok(), ans);
  1011. }
  1012. check("10", Some(10));
  1013. check("1", Some(1));
  1014. check("0", Some(0));
  1015. check("-1", Some(-1));
  1016. check("-10", Some(-10));
  1017. check("+10", Some(10));
  1018. check("--7", None);
  1019. check("++5", None);
  1020. check("+-9", None);
  1021. check("-+3", None);
  1022. check("Z", None);
  1023. check("_", None);
  1024. // issue 10522, this hit an edge case that caused it to
  1025. // attempt to allocate a vector of size (-1u) == huge.
  1026. let x: BigInt = format!("1{}", repeat("0").take(36).collect::<String>())
  1027. .parse()
  1028. .unwrap();
  1029. let _y = x.to_string();
  1030. }
  1031. #[test]
  1032. fn test_lower_hex() {
  1033. let a = BigInt::parse_bytes(b"A", 16).unwrap();
  1034. let hello = BigInt::parse_bytes(b"-22405534230753963835153736737", 10).unwrap();
  1035. assert_eq!(format!("{:x}", a), "a");
  1036. assert_eq!(format!("{:x}", hello), "-48656c6c6f20776f726c6421");
  1037. assert_eq!(format!("{:♥>+#8x}", a), "♥♥♥♥+0xa");
  1038. }
  1039. #[test]
  1040. fn test_upper_hex() {
  1041. let a = BigInt::parse_bytes(b"A", 16).unwrap();
  1042. let hello = BigInt::parse_bytes(b"-22405534230753963835153736737", 10).unwrap();
  1043. assert_eq!(format!("{:X}", a), "A");
  1044. assert_eq!(format!("{:X}", hello), "-48656C6C6F20776F726C6421");
  1045. assert_eq!(format!("{:♥>+#8X}", a), "♥♥♥♥+0xA");
  1046. }
  1047. #[test]
  1048. fn test_binary() {
  1049. let a = BigInt::parse_bytes(b"A", 16).unwrap();
  1050. let hello = BigInt::parse_bytes(b"-224055342307539", 10).unwrap();
  1051. assert_eq!(format!("{:b}", a), "1010");
  1052. assert_eq!(
  1053. format!("{:b}", hello),
  1054. "-110010111100011011110011000101101001100011010011"
  1055. );
  1056. assert_eq!(format!("{:♥>+#8b}", a), "♥+0b1010");
  1057. }
  1058. #[test]
  1059. fn test_octal() {
  1060. let a = BigInt::parse_bytes(b"A", 16).unwrap();
  1061. let hello = BigInt::parse_bytes(b"-22405534230753963835153736737", 10).unwrap();
  1062. assert_eq!(format!("{:o}", a), "12");
  1063. assert_eq!(format!("{:o}", hello), "-22062554330674403566756233062041");
  1064. assert_eq!(format!("{:♥>+#8o}", a), "♥♥♥+0o12");
  1065. }
  1066. #[test]
  1067. fn test_display() {
  1068. let a = BigInt::parse_bytes(b"A", 16).unwrap();
  1069. let hello = BigInt::parse_bytes(b"-22405534230753963835153736737", 10).unwrap();
  1070. assert_eq!(format!("{}", a), "10");
  1071. assert_eq!(format!("{}", hello), "-22405534230753963835153736737");
  1072. assert_eq!(format!("{:♥>+#8}", a), "♥♥♥♥♥+10");
  1073. }
  1074. #[test]
  1075. fn test_neg() {
  1076. assert!(-BigInt::new(Plus, vec![1, 1, 1]) == BigInt::new(Minus, vec![1, 1, 1]));
  1077. assert!(-BigInt::new(Minus, vec![1, 1, 1]) == BigInt::new(Plus, vec![1, 1, 1]));
  1078. let zero: BigInt = Zero::zero();
  1079. assert_eq!(-&zero, zero);
  1080. }
  1081. #[test]
  1082. fn test_negative_shr() {
  1083. assert_eq!(BigInt::from(-1) >> 1, BigInt::from(-1));
  1084. assert_eq!(BigInt::from(-2) >> 1, BigInt::from(-1));
  1085. assert_eq!(BigInt::from(-3) >> 1, BigInt::from(-2));
  1086. assert_eq!(BigInt::from(-3) >> 2, BigInt::from(-1));
  1087. }
  1088. #[test]
  1089. fn test_iter_sum() {
  1090. let result: BigInt = FromPrimitive::from_isize(-1234567).unwrap();
  1091. let data: Vec<BigInt> = vec![
  1092. FromPrimitive::from_i32(-1000000).unwrap(),
  1093. FromPrimitive::from_i32(-200000).unwrap(),
  1094. FromPrimitive::from_i32(-30000).unwrap(),
  1095. FromPrimitive::from_i32(-4000).unwrap(),
  1096. FromPrimitive::from_i32(-500).unwrap(),
  1097. FromPrimitive::from_i32(-60).unwrap(),
  1098. FromPrimitive::from_i32(-7).unwrap(),
  1099. ];
  1100. assert_eq!(result, data.iter().sum::<BigInt>());
  1101. assert_eq!(result, data.into_iter().sum::<BigInt>());
  1102. }
  1103. #[test]
  1104. fn test_iter_product() {
  1105. let data: Vec<BigInt> = vec![
  1106. FromPrimitive::from_i32(1001).unwrap(),
  1107. FromPrimitive::from_i32(-1002).unwrap(),
  1108. FromPrimitive::from_i32(1003).unwrap(),
  1109. FromPrimitive::from_i32(-1004).unwrap(),
  1110. FromPrimitive::from_i32(1005).unwrap(),
  1111. ];
  1112. let result = data.get(0).unwrap()
  1113. * data.get(1).unwrap()
  1114. * data.get(2).unwrap()
  1115. * data.get(3).unwrap()
  1116. * data.get(4).unwrap();
  1117. assert_eq!(result, data.iter().product::<BigInt>());
  1118. assert_eq!(result, data.into_iter().product::<BigInt>());
  1119. }
  1120. #[test]
  1121. fn test_iter_sum_generic() {
  1122. let result: BigInt = FromPrimitive::from_isize(-1234567).unwrap();
  1123. let data = vec![-1000000, -200000, -30000, -4000, -500, -60, -7];
  1124. assert_eq!(result, data.iter().sum::<BigInt>());
  1125. assert_eq!(result, data.into_iter().sum::<BigInt>());
  1126. }
  1127. #[test]
  1128. fn test_iter_product_generic() {
  1129. let data = vec![1001, -1002, 1003, -1004, 1005];
  1130. let result = data[0].to_bigint().unwrap()
  1131. * data[1].to_bigint().unwrap()
  1132. * data[2].to_bigint().unwrap()
  1133. * data[3].to_bigint().unwrap()
  1134. * data[4].to_bigint().unwrap();
  1135. assert_eq!(result, data.iter().product::<BigInt>());
  1136. assert_eq!(result, data.into_iter().product::<BigInt>());
  1137. }
  1138. #[test]
  1139. fn test_pow() {
  1140. let one = BigInt::from(1i32);
  1141. let two = BigInt::from(2i32);
  1142. let four = BigInt::from(4i32);
  1143. let eight = BigInt::from(8i32);
  1144. let minus_two = BigInt::from(-2i32);
  1145. macro_rules! check {
  1146. ($t:ty) => {
  1147. assert_eq!(Pow::pow(&two, 0 as $t), one);
  1148. assert_eq!(Pow::pow(&two, 1 as $t), two);
  1149. assert_eq!(Pow::pow(&two, 2 as $t), four);
  1150. assert_eq!(Pow::pow(&two, 3 as $t), eight);
  1151. assert_eq!(Pow::pow(&two, &(3 as $t)), eight);
  1152. assert_eq!(Pow::pow(&minus_two, 0 as $t), one, "-2^0");
  1153. assert_eq!(Pow::pow(&minus_two, 1 as $t), minus_two, "-2^1");
  1154. assert_eq!(Pow::pow(&minus_two, 2 as $t), four, "-2^2");
  1155. assert_eq!(Pow::pow(&minus_two, 3 as $t), -&eight, "-2^3");
  1156. };
  1157. }
  1158. check!(u8);
  1159. check!(u16);
  1160. check!(u32);
  1161. check!(u64);
  1162. check!(usize);
  1163. let pow_1e10000 = BigInt::from(10u32).pow(10_000_u32);
  1164. let manual_1e10000 = repeat(10u32).take(10_000).product::<BigInt>();
  1165. assert!(manual_1e10000 == pow_1e10000);
  1166. }
  1167. #[test]
  1168. fn test_bit() {
  1169. // 12 = (1100)_2
  1170. assert!(!BigInt::from(0b1100u8).bit(0));
  1171. assert!(!BigInt::from(0b1100u8).bit(1));
  1172. assert!(BigInt::from(0b1100u8).bit(2));
  1173. assert!(BigInt::from(0b1100u8).bit(3));
  1174. assert!(!BigInt::from(0b1100u8).bit(4));
  1175. assert!(!BigInt::from(0b1100u8).bit(200));
  1176. assert!(!BigInt::from(0b1100u8).bit(u64::MAX));
  1177. // -12 = (...110100)_2
  1178. assert!(!BigInt::from(-12i8).bit(0));
  1179. assert!(!BigInt::from(-12i8).bit(1));
  1180. assert!(BigInt::from(-12i8).bit(2));
  1181. assert!(!BigInt::from(-12i8).bit(3));
  1182. assert!(BigInt::from(-12i8).bit(4));
  1183. assert!(BigInt::from(-12i8).bit(200));
  1184. assert!(BigInt::from(-12i8).bit(u64::MAX));
  1185. }
  1186. #[test]
  1187. fn test_set_bit() {
  1188. let mut x: BigInt;
  1189. // zero
  1190. x = BigInt::zero();
  1191. x.set_bit(200, true);
  1192. assert_eq!(x, BigInt::one() << 200);
  1193. x = BigInt::zero();
  1194. x.set_bit(200, false);
  1195. assert_eq!(x, BigInt::zero());
  1196. // positive numbers
  1197. x = BigInt::from_biguint(Plus, BigUint::one() << 200);
  1198. x.set_bit(10, true);
  1199. x.set_bit(200, false);
  1200. assert_eq!(x, BigInt::one() << 10);
  1201. x.set_bit(10, false);
  1202. x.set_bit(5, false);
  1203. assert_eq!(x, BigInt::zero());
  1204. // negative numbers
  1205. x = BigInt::from(-12i8);
  1206. x.set_bit(200, true);
  1207. assert_eq!(x, BigInt::from(-12i8));
  1208. x.set_bit(200, false);
  1209. assert_eq!(
  1210. x,
  1211. BigInt::from_biguint(Minus, BigUint::from(12u8) | (BigUint::one() << 200))
  1212. );
  1213. x.set_bit(6, false);
  1214. assert_eq!(
  1215. x,
  1216. BigInt::from_biguint(Minus, BigUint::from(76u8) | (BigUint::one() << 200))
  1217. );
  1218. x.set_bit(6, true);
  1219. assert_eq!(
  1220. x,
  1221. BigInt::from_biguint(Minus, BigUint::from(12u8) | (BigUint::one() << 200))
  1222. );
  1223. x.set_bit(200, true);
  1224. assert_eq!(x, BigInt::from(-12i8));
  1225. x = BigInt::from_biguint(Minus, BigUint::one() << 30);
  1226. x.set_bit(10, true);
  1227. assert_eq!(
  1228. x,
  1229. BigInt::from_biguint(Minus, (BigUint::one() << 30) - (BigUint::one() << 10))
  1230. );
  1231. x = BigInt::from_biguint(Minus, BigUint::one() << 200);
  1232. x.set_bit(40, true);
  1233. assert_eq!(
  1234. x,
  1235. BigInt::from_biguint(Minus, (BigUint::one() << 200) - (BigUint::one() << 40))
  1236. );
  1237. x = BigInt::from_biguint(Minus, (BigUint::one() << 200) | (BigUint::one() << 100));
  1238. x.set_bit(100, false);
  1239. assert_eq!(
  1240. x,
  1241. BigInt::from_biguint(Minus, (BigUint::one() << 200) | (BigUint::one() << 101))
  1242. );
  1243. x = BigInt::from_biguint(Minus, (BigUint::one() << 63) | (BigUint::one() << 62));
  1244. x.set_bit(62, false);
  1245. assert_eq!(x, BigInt::from_biguint(Minus, BigUint::one() << 64));
  1246. x = BigInt::from_biguint(Minus, (BigUint::one() << 200) - BigUint::one());
  1247. x.set_bit(0, false);
  1248. assert_eq!(x, BigInt::from_biguint(Minus, BigUint::one() << 200));
  1249. }