BigInteger.cs 102 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. using System;
  3. using System.Collections;
  4. using System.Diagnostics;
  5. using System.Globalization;
  6. using System.Text;
  7. using Org.BouncyCastle.Security;
  8. using Org.BouncyCastle.Utilities;
  9. namespace Org.BouncyCastle.Math
  10. {
  11. #if !(NETCF_1_0 || NETCF_2_0 || SILVERLIGHT || NETFX_CORE || PORTABLE)
  12. [Serializable]
  13. #endif
  14. public class BigInteger
  15. {
  16. // The first few odd primes
  17. /*
  18. 3 5 7 11 13 17 19 23 29
  19. 31 37 41 43 47 53 59 61 67 71
  20. 73 79 83 89 97 101 103 107 109 113
  21. 127 131 137 139 149 151 157 163 167 173
  22. 179 181 191 193 197 199 211 223 227 229
  23. 233 239 241 251 257 263 269 271 277 281
  24. 283 293 307 311 313 317 331 337 347 349
  25. 353 359 367 373 379 383 389 397 401 409
  26. 419 421 431 433 439 443 449 457 461 463
  27. 467 479 487 491 499 503 509 521 523 541
  28. 547 557 563 569 571 577 587 593 599 601
  29. 607 613 617 619 631 641 643 647 653 659
  30. 661 673 677 683 691 701 709 719 727 733
  31. 739 743 751 757 761 769 773 787 797 809
  32. 811 821 823 827 829 839 853 857 859 863
  33. 877 881 883 887 907 911 919 929 937 941
  34. 947 953 967 971 977 983 991 997 1009
  35. 1013 1019 1021 1031 1033 1039 1049 1051
  36. 1061 1063 1069 1087 1091 1093 1097 1103
  37. 1109 1117 1123 1129 1151 1153 1163 1171
  38. 1181 1187 1193 1201 1213 1217 1223 1229
  39. 1231 1237 1249 1259 1277 1279 1283 1289
  40. */
  41. // Each list has a product < 2^31
  42. internal static readonly int[][] primeLists = new int[][]
  43. {
  44. new int[]{ 3, 5, 7, 11, 13, 17, 19, 23 },
  45. new int[]{ 29, 31, 37, 41, 43 },
  46. new int[]{ 47, 53, 59, 61, 67 },
  47. new int[]{ 71, 73, 79, 83 },
  48. new int[]{ 89, 97, 101, 103 },
  49. new int[]{ 107, 109, 113, 127 },
  50. new int[]{ 131, 137, 139, 149 },
  51. new int[]{ 151, 157, 163, 167 },
  52. new int[]{ 173, 179, 181, 191 },
  53. new int[]{ 193, 197, 199, 211 },
  54. new int[]{ 223, 227, 229 },
  55. new int[]{ 233, 239, 241 },
  56. new int[]{ 251, 257, 263 },
  57. new int[]{ 269, 271, 277 },
  58. new int[]{ 281, 283, 293 },
  59. new int[]{ 307, 311, 313 },
  60. new int[]{ 317, 331, 337 },
  61. new int[]{ 347, 349, 353 },
  62. new int[]{ 359, 367, 373 },
  63. new int[]{ 379, 383, 389 },
  64. new int[]{ 397, 401, 409 },
  65. new int[]{ 419, 421, 431 },
  66. new int[]{ 433, 439, 443 },
  67. new int[]{ 449, 457, 461 },
  68. new int[]{ 463, 467, 479 },
  69. new int[]{ 487, 491, 499 },
  70. new int[]{ 503, 509, 521 },
  71. new int[]{ 523, 541, 547 },
  72. new int[]{ 557, 563, 569 },
  73. new int[]{ 571, 577, 587 },
  74. new int[]{ 593, 599, 601 },
  75. new int[]{ 607, 613, 617 },
  76. new int[]{ 619, 631, 641 },
  77. new int[]{ 643, 647, 653 },
  78. new int[]{ 659, 661, 673 },
  79. new int[]{ 677, 683, 691 },
  80. new int[]{ 701, 709, 719 },
  81. new int[]{ 727, 733, 739 },
  82. new int[]{ 743, 751, 757 },
  83. new int[]{ 761, 769, 773 },
  84. new int[]{ 787, 797, 809 },
  85. new int[]{ 811, 821, 823 },
  86. new int[]{ 827, 829, 839 },
  87. new int[]{ 853, 857, 859 },
  88. new int[]{ 863, 877, 881 },
  89. new int[]{ 883, 887, 907 },
  90. new int[]{ 911, 919, 929 },
  91. new int[]{ 937, 941, 947 },
  92. new int[]{ 953, 967, 971 },
  93. new int[]{ 977, 983, 991 },
  94. new int[]{ 997, 1009, 1013 },
  95. new int[]{ 1019, 1021, 1031 },
  96. new int[]{ 1033, 1039, 1049 },
  97. new int[]{ 1051, 1061, 1063 },
  98. new int[]{ 1069, 1087, 1091 },
  99. new int[]{ 1093, 1097, 1103 },
  100. new int[]{ 1109, 1117, 1123 },
  101. new int[]{ 1129, 1151, 1153 },
  102. new int[]{ 1163, 1171, 1181 },
  103. new int[]{ 1187, 1193, 1201 },
  104. new int[]{ 1213, 1217, 1223 },
  105. new int[]{ 1229, 1231, 1237 },
  106. new int[]{ 1249, 1259, 1277 },
  107. new int[]{ 1279, 1283, 1289 },
  108. };
  109. internal static readonly int[] primeProducts;
  110. private const long IMASK = 0xFFFFFFFFL;
  111. private const ulong UIMASK = 0xFFFFFFFFUL;
  112. private static readonly int[] ZeroMagnitude = new int[0];
  113. private static readonly byte[] ZeroEncoding = new byte[0];
  114. private static readonly BigInteger[] SMALL_CONSTANTS = new BigInteger[17];
  115. public static readonly BigInteger Zero;
  116. public static readonly BigInteger One;
  117. public static readonly BigInteger Two;
  118. public static readonly BigInteger Three;
  119. public static readonly BigInteger Ten;
  120. //private readonly static byte[] BitCountTable =
  121. //{
  122. // 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,
  123. // 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  124. // 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  125. // 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  126. // 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  127. // 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  128. // 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  129. // 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  130. // 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  131. // 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  132. // 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  133. // 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  134. // 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  135. // 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  136. // 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  137. // 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8
  138. //};
  139. private readonly static byte[] BitLengthTable =
  140. {
  141. 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
  142. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  143. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  144. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  145. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  146. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  147. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  148. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  149. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  150. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  151. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  152. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  153. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  154. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  155. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  156. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8
  157. };
  158. // TODO Parse radix-2 64 bits at a time and radix-8 63 bits at a time
  159. private const int chunk2 = 1, chunk8 = 1, chunk10 = 19, chunk16 = 16;
  160. private static readonly BigInteger radix2, radix2E, radix8, radix8E, radix10, radix10E, radix16, radix16E;
  161. private static readonly SecureRandom RandomSource = new SecureRandom();
  162. /*
  163. * These are the threshold bit-lengths (of an exponent) where we increase the window size.
  164. * They are calculated according to the expected savings in multiplications.
  165. * Some squares will also be saved on average, but we offset these against the extra storage costs.
  166. */
  167. private static readonly int[] ExpWindowThresholds = { 7, 25, 81, 241, 673, 1793, 4609, Int32.MaxValue };
  168. private const int BitsPerByte = 8;
  169. private const int BitsPerInt = 32;
  170. private const int BytesPerInt = 4;
  171. static BigInteger()
  172. {
  173. Zero = new BigInteger(0, ZeroMagnitude, false);
  174. Zero.nBits = 0; Zero.nBitLength = 0;
  175. SMALL_CONSTANTS[0] = Zero;
  176. for (uint i = 1; i < SMALL_CONSTANTS.Length; ++i)
  177. {
  178. SMALL_CONSTANTS[i] = CreateUValueOf(i);
  179. }
  180. One = SMALL_CONSTANTS[1];
  181. Two = SMALL_CONSTANTS[2];
  182. Three = SMALL_CONSTANTS[3];
  183. Ten = SMALL_CONSTANTS[10];
  184. radix2 = ValueOf(2);
  185. radix2E = radix2.Pow(chunk2);
  186. radix8 = ValueOf(8);
  187. radix8E = radix8.Pow(chunk8);
  188. radix10 = ValueOf(10);
  189. radix10E = radix10.Pow(chunk10);
  190. radix16 = ValueOf(16);
  191. radix16E = radix16.Pow(chunk16);
  192. primeProducts = new int[primeLists.Length];
  193. for (int i = 0; i < primeLists.Length; ++i)
  194. {
  195. int[] primeList = primeLists[i];
  196. int product = primeList[0];
  197. for (int j = 1; j < primeList.Length; ++j)
  198. {
  199. product *= primeList[j];
  200. }
  201. primeProducts[i] = product;
  202. }
  203. }
  204. private int[] magnitude; // array of ints with [0] being the most significant
  205. private int sign; // -1 means -ve; +1 means +ve; 0 means 0;
  206. private int nBits = -1; // cache BitCount() value
  207. private int nBitLength = -1; // cache BitLength() value
  208. private int mQuote = 0; // -m^(-1) mod b, b = 2^32 (see Montgomery mult.), 0 when uninitialised
  209. private static int GetByteLength(
  210. int nBits)
  211. {
  212. return (nBits + BitsPerByte - 1) / BitsPerByte;
  213. }
  214. internal static BigInteger Arbitrary(int sizeInBits)
  215. {
  216. return new BigInteger(sizeInBits, RandomSource);
  217. }
  218. private BigInteger(
  219. int signum,
  220. int[] mag,
  221. bool checkMag)
  222. {
  223. if (checkMag)
  224. {
  225. int i = 0;
  226. while (i < mag.Length && mag[i] == 0)
  227. {
  228. ++i;
  229. }
  230. if (i == mag.Length)
  231. {
  232. this.sign = 0;
  233. this.magnitude = ZeroMagnitude;
  234. }
  235. else
  236. {
  237. this.sign = signum;
  238. if (i == 0)
  239. {
  240. this.magnitude = mag;
  241. }
  242. else
  243. {
  244. // strip leading 0 words
  245. this.magnitude = new int[mag.Length - i];
  246. Array.Copy(mag, i, this.magnitude, 0, this.magnitude.Length);
  247. }
  248. }
  249. }
  250. else
  251. {
  252. this.sign = signum;
  253. this.magnitude = mag;
  254. }
  255. }
  256. public BigInteger(
  257. string value)
  258. : this(value, 10)
  259. {
  260. }
  261. public BigInteger(
  262. string str,
  263. int radix)
  264. {
  265. if (str.Length == 0)
  266. throw new FormatException("Zero length BigInteger");
  267. NumberStyles style;
  268. int chunk;
  269. BigInteger r;
  270. BigInteger rE;
  271. switch (radix)
  272. {
  273. case 2:
  274. // Is there anyway to restrict to binary digits?
  275. style = NumberStyles.Integer;
  276. chunk = chunk2;
  277. r = radix2;
  278. rE = radix2E;
  279. break;
  280. case 8:
  281. // Is there anyway to restrict to octal digits?
  282. style = NumberStyles.Integer;
  283. chunk = chunk8;
  284. r = radix8;
  285. rE = radix8E;
  286. break;
  287. case 10:
  288. // This style seems to handle spaces and minus sign already (our processing redundant?)
  289. style = NumberStyles.Integer;
  290. chunk = chunk10;
  291. r = radix10;
  292. rE = radix10E;
  293. break;
  294. case 16:
  295. // TODO Should this be HexNumber?
  296. style = NumberStyles.AllowHexSpecifier;
  297. chunk = chunk16;
  298. r = radix16;
  299. rE = radix16E;
  300. break;
  301. default:
  302. throw new FormatException("Only bases 2, 8, 10, or 16 allowed");
  303. }
  304. int index = 0;
  305. sign = 1;
  306. if (str[0] == '-')
  307. {
  308. if (str.Length == 1)
  309. throw new FormatException("Zero length BigInteger");
  310. sign = -1;
  311. index = 1;
  312. }
  313. // strip leading zeros from the string str
  314. while (index < str.Length && Int32.Parse(str[index].ToString(), style) == 0)
  315. {
  316. index++;
  317. }
  318. if (index >= str.Length)
  319. {
  320. // zero value - we're done
  321. sign = 0;
  322. magnitude = ZeroMagnitude;
  323. return;
  324. }
  325. //////
  326. // could we work out the max number of ints required to store
  327. // str.Length digits in the given base, then allocate that
  328. // storage in one hit?, then Generate the magnitude in one hit too?
  329. //////
  330. BigInteger b = Zero;
  331. int next = index + chunk;
  332. if (next <= str.Length)
  333. {
  334. do
  335. {
  336. string s = str.Substring(index, chunk);
  337. ulong i = ulong.Parse(s, style);
  338. BigInteger bi = CreateUValueOf(i);
  339. switch (radix)
  340. {
  341. case 2:
  342. // TODO Need this because we are parsing in radix 10 above
  343. if (i >= 2)
  344. throw new FormatException("Bad character in radix 2 string: " + s);
  345. // TODO Parse 64 bits at a time
  346. b = b.ShiftLeft(1);
  347. break;
  348. case 8:
  349. // TODO Need this because we are parsing in radix 10 above
  350. if (i >= 8)
  351. throw new FormatException("Bad character in radix 8 string: " + s);
  352. // TODO Parse 63 bits at a time
  353. b = b.ShiftLeft(3);
  354. break;
  355. case 16:
  356. b = b.ShiftLeft(64);
  357. break;
  358. default:
  359. b = b.Multiply(rE);
  360. break;
  361. }
  362. b = b.Add(bi);
  363. index = next;
  364. next += chunk;
  365. }
  366. while (next <= str.Length);
  367. }
  368. if (index < str.Length)
  369. {
  370. string s = str.Substring(index);
  371. ulong i = ulong.Parse(s, style);
  372. BigInteger bi = CreateUValueOf(i);
  373. if (b.sign > 0)
  374. {
  375. if (radix == 2)
  376. {
  377. // NB: Can't reach here since we are parsing one char at a time
  378. Debug.Assert(false);
  379. // TODO Parse all bits at once
  380. // b = b.ShiftLeft(s.Length);
  381. }
  382. else if (radix == 8)
  383. {
  384. // NB: Can't reach here since we are parsing one char at a time
  385. Debug.Assert(false);
  386. // TODO Parse all bits at once
  387. // b = b.ShiftLeft(s.Length * 3);
  388. }
  389. else if (radix == 16)
  390. {
  391. b = b.ShiftLeft(s.Length << 2);
  392. }
  393. else
  394. {
  395. b = b.Multiply(r.Pow(s.Length));
  396. }
  397. b = b.Add(bi);
  398. }
  399. else
  400. {
  401. b = bi;
  402. }
  403. }
  404. // Note: This is the previous (slower) algorithm
  405. // while (index < value.Length)
  406. // {
  407. // char c = value[index];
  408. // string s = c.ToString();
  409. // int i = Int32.Parse(s, style);
  410. //
  411. // b = b.Multiply(r).Add(ValueOf(i));
  412. // index++;
  413. // }
  414. magnitude = b.magnitude;
  415. }
  416. public BigInteger(
  417. byte[] bytes)
  418. : this(bytes, 0, bytes.Length)
  419. {
  420. }
  421. public BigInteger(
  422. byte[] bytes,
  423. int offset,
  424. int length)
  425. {
  426. if (length == 0)
  427. throw new FormatException("Zero length BigInteger");
  428. // TODO Move this processing into MakeMagnitude (provide sign argument)
  429. if ((sbyte)bytes[offset] < 0)
  430. {
  431. this.sign = -1;
  432. int end = offset + length;
  433. int iBval;
  434. // strip leading sign bytes
  435. for (iBval = offset; iBval < end && ((sbyte)bytes[iBval] == -1); iBval++)
  436. {
  437. }
  438. if (iBval >= end)
  439. {
  440. this.magnitude = One.magnitude;
  441. }
  442. else
  443. {
  444. int numBytes = end - iBval;
  445. byte[] inverse = new byte[numBytes];
  446. int index = 0;
  447. while (index < numBytes)
  448. {
  449. inverse[index++] = (byte)~bytes[iBval++];
  450. }
  451. Debug.Assert(iBval == end);
  452. while (inverse[--index] == byte.MaxValue)
  453. {
  454. inverse[index] = byte.MinValue;
  455. }
  456. inverse[index]++;
  457. this.magnitude = MakeMagnitude(inverse, 0, inverse.Length);
  458. }
  459. }
  460. else
  461. {
  462. // strip leading zero bytes and return magnitude bytes
  463. this.magnitude = MakeMagnitude(bytes, offset, length);
  464. this.sign = this.magnitude.Length > 0 ? 1 : 0;
  465. }
  466. }
  467. private static int[] MakeMagnitude(
  468. byte[] bytes,
  469. int offset,
  470. int length)
  471. {
  472. int end = offset + length;
  473. // strip leading zeros
  474. int firstSignificant;
  475. for (firstSignificant = offset; firstSignificant < end
  476. && bytes[firstSignificant] == 0; firstSignificant++)
  477. {
  478. }
  479. if (firstSignificant >= end)
  480. {
  481. return ZeroMagnitude;
  482. }
  483. int nInts = (end - firstSignificant + 3) / BytesPerInt;
  484. int bCount = (end - firstSignificant) % BytesPerInt;
  485. if (bCount == 0)
  486. {
  487. bCount = BytesPerInt;
  488. }
  489. if (nInts < 1)
  490. {
  491. return ZeroMagnitude;
  492. }
  493. int[] mag = new int[nInts];
  494. int v = 0;
  495. int magnitudeIndex = 0;
  496. for (int i = firstSignificant; i < end; ++i)
  497. {
  498. v <<= 8;
  499. v |= bytes[i] & 0xff;
  500. bCount--;
  501. if (bCount <= 0)
  502. {
  503. mag[magnitudeIndex] = v;
  504. magnitudeIndex++;
  505. bCount = BytesPerInt;
  506. v = 0;
  507. }
  508. }
  509. if (magnitudeIndex < mag.Length)
  510. {
  511. mag[magnitudeIndex] = v;
  512. }
  513. return mag;
  514. }
  515. public BigInteger(
  516. int sign,
  517. byte[] bytes)
  518. : this(sign, bytes, 0, bytes.Length)
  519. {
  520. }
  521. public BigInteger(
  522. int sign,
  523. byte[] bytes,
  524. int offset,
  525. int length)
  526. {
  527. if (sign < -1 || sign > 1)
  528. throw new FormatException("Invalid sign value");
  529. if (sign == 0)
  530. {
  531. this.sign = 0;
  532. this.magnitude = ZeroMagnitude;
  533. }
  534. else
  535. {
  536. // copy bytes
  537. this.magnitude = MakeMagnitude(bytes, offset, length);
  538. this.sign = this.magnitude.Length < 1 ? 0 : sign;
  539. }
  540. }
  541. public BigInteger(
  542. int sizeInBits,
  543. Random random)
  544. {
  545. if (sizeInBits < 0)
  546. throw new ArgumentException("sizeInBits must be non-negative");
  547. this.nBits = -1;
  548. this.nBitLength = -1;
  549. if (sizeInBits == 0)
  550. {
  551. this.sign = 0;
  552. this.magnitude = ZeroMagnitude;
  553. return;
  554. }
  555. int nBytes = GetByteLength(sizeInBits);
  556. byte[] b = new byte[nBytes];
  557. random.NextBytes(b);
  558. // strip off any excess bits in the MSB
  559. int xBits = BitsPerByte * nBytes - sizeInBits;
  560. b[0] &= (byte)(255U >> xBits);
  561. this.magnitude = MakeMagnitude(b, 0, b.Length);
  562. this.sign = this.magnitude.Length < 1 ? 0 : 1;
  563. }
  564. public BigInteger(
  565. int bitLength,
  566. int certainty,
  567. Random random)
  568. {
  569. if (bitLength < 2)
  570. throw new ArithmeticException("bitLength < 2");
  571. this.sign = 1;
  572. this.nBitLength = bitLength;
  573. if (bitLength == 2)
  574. {
  575. this.magnitude = random.Next(2) == 0
  576. ? Two.magnitude
  577. : Three.magnitude;
  578. return;
  579. }
  580. int nBytes = GetByteLength(bitLength);
  581. byte[] b = new byte[nBytes];
  582. int xBits = BitsPerByte * nBytes - bitLength;
  583. byte mask = (byte)(255U >> xBits);
  584. byte lead = (byte)(1 << (7 - xBits));
  585. for (;;)
  586. {
  587. random.NextBytes(b);
  588. // strip off any excess bits in the MSB
  589. b[0] &= mask;
  590. // ensure the leading bit is 1 (to meet the strength requirement)
  591. b[0] |= lead;
  592. // ensure the trailing bit is 1 (i.e. must be odd)
  593. b[nBytes - 1] |= 1;
  594. this.magnitude = MakeMagnitude(b, 0, b.Length);
  595. this.nBits = -1;
  596. this.mQuote = 0;
  597. if (certainty < 1)
  598. break;
  599. if (CheckProbablePrime(certainty, random, true))
  600. break;
  601. for (int j = 1; j < (magnitude.Length - 1); ++j)
  602. {
  603. this.magnitude[j] ^= random.Next();
  604. if (CheckProbablePrime(certainty, random, true))
  605. return;
  606. }
  607. }
  608. }
  609. public BigInteger Abs()
  610. {
  611. return sign >= 0 ? this : Negate();
  612. }
  613. /**
  614. * return a = a + b - b preserved.
  615. */
  616. private static int[] AddMagnitudes(
  617. int[] a,
  618. int[] b)
  619. {
  620. int tI = a.Length - 1;
  621. int vI = b.Length - 1;
  622. long m = 0;
  623. while (vI >= 0)
  624. {
  625. m += ((long)(uint)a[tI] + (long)(uint)b[vI--]);
  626. a[tI--] = (int)m;
  627. m = (long)((ulong)m >> 32);
  628. }
  629. if (m != 0)
  630. {
  631. while (tI >= 0 && ++a[tI--] == 0)
  632. {
  633. }
  634. }
  635. return a;
  636. }
  637. public BigInteger Add(
  638. BigInteger value)
  639. {
  640. if (this.sign == 0)
  641. return value;
  642. if (this.sign != value.sign)
  643. {
  644. if (value.sign == 0)
  645. return this;
  646. if (value.sign < 0)
  647. return Subtract(value.Negate());
  648. return value.Subtract(Negate());
  649. }
  650. return AddToMagnitude(value.magnitude);
  651. }
  652. private BigInteger AddToMagnitude(
  653. int[] magToAdd)
  654. {
  655. int[] big, small;
  656. if (this.magnitude.Length < magToAdd.Length)
  657. {
  658. big = magToAdd;
  659. small = this.magnitude;
  660. }
  661. else
  662. {
  663. big = this.magnitude;
  664. small = magToAdd;
  665. }
  666. // Conservatively avoid over-allocation when no overflow possible
  667. uint limit = uint.MaxValue;
  668. if (big.Length == small.Length)
  669. limit -= (uint) small[0];
  670. bool possibleOverflow = (uint) big[0] >= limit;
  671. int[] bigCopy;
  672. if (possibleOverflow)
  673. {
  674. bigCopy = new int[big.Length + 1];
  675. big.CopyTo(bigCopy, 1);
  676. }
  677. else
  678. {
  679. bigCopy = (int[]) big.Clone();
  680. }
  681. bigCopy = AddMagnitudes(bigCopy, small);
  682. return new BigInteger(this.sign, bigCopy, possibleOverflow);
  683. }
  684. public BigInteger And(
  685. BigInteger value)
  686. {
  687. if (this.sign == 0 || value.sign == 0)
  688. {
  689. return Zero;
  690. }
  691. int[] aMag = this.sign > 0
  692. ? this.magnitude
  693. : Add(One).magnitude;
  694. int[] bMag = value.sign > 0
  695. ? value.magnitude
  696. : value.Add(One).magnitude;
  697. bool resultNeg = sign < 0 && value.sign < 0;
  698. int resultLength = System.Math.Max(aMag.Length, bMag.Length);
  699. int[] resultMag = new int[resultLength];
  700. int aStart = resultMag.Length - aMag.Length;
  701. int bStart = resultMag.Length - bMag.Length;
  702. for (int i = 0; i < resultMag.Length; ++i)
  703. {
  704. int aWord = i >= aStart ? aMag[i - aStart] : 0;
  705. int bWord = i >= bStart ? bMag[i - bStart] : 0;
  706. if (this.sign < 0)
  707. {
  708. aWord = ~aWord;
  709. }
  710. if (value.sign < 0)
  711. {
  712. bWord = ~bWord;
  713. }
  714. resultMag[i] = aWord & bWord;
  715. if (resultNeg)
  716. {
  717. resultMag[i] = ~resultMag[i];
  718. }
  719. }
  720. BigInteger result = new BigInteger(1, resultMag, true);
  721. // TODO Optimise this case
  722. if (resultNeg)
  723. {
  724. result = result.Not();
  725. }
  726. return result;
  727. }
  728. public BigInteger AndNot(
  729. BigInteger val)
  730. {
  731. return And(val.Not());
  732. }
  733. public int BitCount
  734. {
  735. get
  736. {
  737. if (nBits == -1)
  738. {
  739. if (sign < 0)
  740. {
  741. // TODO Optimise this case
  742. nBits = Not().BitCount;
  743. }
  744. else
  745. {
  746. int sum = 0;
  747. for (int i = 0; i < magnitude.Length; ++i)
  748. {
  749. sum += BitCnt(magnitude[i]);
  750. }
  751. nBits = sum;
  752. }
  753. }
  754. return nBits;
  755. }
  756. }
  757. public static int BitCnt(int i)
  758. {
  759. uint u = (uint)i;
  760. u = u - ((u >> 1) & 0x55555555);
  761. u = (u & 0x33333333) + ((u >> 2) & 0x33333333);
  762. u = (u + (u >> 4)) & 0x0f0f0f0f;
  763. u += (u >> 8);
  764. u += (u >> 16);
  765. u &= 0x3f;
  766. return (int)u;
  767. }
  768. private static int CalcBitLength(int sign, int indx, int[] mag)
  769. {
  770. for (;;)
  771. {
  772. if (indx >= mag.Length)
  773. return 0;
  774. if (mag[indx] != 0)
  775. break;
  776. ++indx;
  777. }
  778. // bit length for everything after the first int
  779. int bitLength = 32 * ((mag.Length - indx) - 1);
  780. // and determine bitlength of first int
  781. int firstMag = mag[indx];
  782. bitLength += BitLen(firstMag);
  783. // Check for negative powers of two
  784. if (sign < 0 && ((firstMag & -firstMag) == firstMag))
  785. {
  786. do
  787. {
  788. if (++indx >= mag.Length)
  789. {
  790. --bitLength;
  791. break;
  792. }
  793. }
  794. while (mag[indx] == 0);
  795. }
  796. return bitLength;
  797. }
  798. public int BitLength
  799. {
  800. get
  801. {
  802. if (nBitLength == -1)
  803. {
  804. nBitLength = sign == 0
  805. ? 0
  806. : CalcBitLength(sign, 0, magnitude);
  807. }
  808. return nBitLength;
  809. }
  810. }
  811. //
  812. // BitLen(value) is the number of bits in value.
  813. //
  814. internal static int BitLen(int w)
  815. {
  816. uint v = (uint)w;
  817. uint t = v >> 24;
  818. if (t != 0)
  819. return 24 + BitLengthTable[t];
  820. t = v >> 16;
  821. if (t != 0)
  822. return 16 + BitLengthTable[t];
  823. t = v >> 8;
  824. if (t != 0)
  825. return 8 + BitLengthTable[t];
  826. return BitLengthTable[v];
  827. }
  828. private bool QuickPow2Check()
  829. {
  830. return sign > 0 && nBits == 1;
  831. }
  832. public int CompareTo(
  833. object obj)
  834. {
  835. return CompareTo((BigInteger)obj);
  836. }
  837. /**
  838. * unsigned comparison on two arrays - note the arrays may
  839. * start with leading zeros.
  840. */
  841. private static int CompareTo(
  842. int xIndx,
  843. int[] x,
  844. int yIndx,
  845. int[] y)
  846. {
  847. while (xIndx != x.Length && x[xIndx] == 0)
  848. {
  849. xIndx++;
  850. }
  851. while (yIndx != y.Length && y[yIndx] == 0)
  852. {
  853. yIndx++;
  854. }
  855. return CompareNoLeadingZeroes(xIndx, x, yIndx, y);
  856. }
  857. private static int CompareNoLeadingZeroes(
  858. int xIndx,
  859. int[] x,
  860. int yIndx,
  861. int[] y)
  862. {
  863. int diff = (x.Length - y.Length) - (xIndx - yIndx);
  864. if (diff != 0)
  865. {
  866. return diff < 0 ? -1 : 1;
  867. }
  868. // lengths of magnitudes the same, test the magnitude values
  869. while (xIndx < x.Length)
  870. {
  871. uint v1 = (uint)x[xIndx++];
  872. uint v2 = (uint)y[yIndx++];
  873. if (v1 != v2)
  874. return v1 < v2 ? -1 : 1;
  875. }
  876. return 0;
  877. }
  878. public int CompareTo(
  879. BigInteger value)
  880. {
  881. return sign < value.sign ? -1
  882. : sign > value.sign ? 1
  883. : sign == 0 ? 0
  884. : sign * CompareNoLeadingZeroes(0, magnitude, 0, value.magnitude);
  885. }
  886. /**
  887. * return z = x / y - done in place (z value preserved, x contains the
  888. * remainder)
  889. */
  890. private int[] Divide(
  891. int[] x,
  892. int[] y)
  893. {
  894. int xStart = 0;
  895. while (xStart < x.Length && x[xStart] == 0)
  896. {
  897. ++xStart;
  898. }
  899. int yStart = 0;
  900. while (yStart < y.Length && y[yStart] == 0)
  901. {
  902. ++yStart;
  903. }
  904. Debug.Assert(yStart < y.Length);
  905. int xyCmp = CompareNoLeadingZeroes(xStart, x, yStart, y);
  906. int[] count;
  907. if (xyCmp > 0)
  908. {
  909. int yBitLength = CalcBitLength(1, yStart, y);
  910. int xBitLength = CalcBitLength(1, xStart, x);
  911. int shift = xBitLength - yBitLength;
  912. int[] iCount;
  913. int iCountStart = 0;
  914. int[] c;
  915. int cStart = 0;
  916. int cBitLength = yBitLength;
  917. if (shift > 0)
  918. {
  919. // iCount = ShiftLeft(One.magnitude, shift);
  920. iCount = new int[(shift >> 5) + 1];
  921. iCount[0] = 1 << (shift % 32);
  922. c = ShiftLeft(y, shift);
  923. cBitLength += shift;
  924. }
  925. else
  926. {
  927. iCount = new int[] { 1 };
  928. int len = y.Length - yStart;
  929. c = new int[len];
  930. Array.Copy(y, yStart, c, 0, len);
  931. }
  932. count = new int[iCount.Length];
  933. for (;;)
  934. {
  935. if (cBitLength < xBitLength
  936. || CompareNoLeadingZeroes(xStart, x, cStart, c) >= 0)
  937. {
  938. Subtract(xStart, x, cStart, c);
  939. AddMagnitudes(count, iCount);
  940. while (x[xStart] == 0)
  941. {
  942. if (++xStart == x.Length)
  943. return count;
  944. }
  945. //xBitLength = CalcBitLength(xStart, x);
  946. xBitLength = 32 * (x.Length - xStart - 1) + BitLen(x[xStart]);
  947. if (xBitLength <= yBitLength)
  948. {
  949. if (xBitLength < yBitLength)
  950. return count;
  951. xyCmp = CompareNoLeadingZeroes(xStart, x, yStart, y);
  952. if (xyCmp <= 0)
  953. break;
  954. }
  955. }
  956. shift = cBitLength - xBitLength;
  957. // NB: The case where c[cStart] is 1-bit is harmless
  958. if (shift == 1)
  959. {
  960. uint firstC = (uint) c[cStart] >> 1;
  961. uint firstX = (uint) x[xStart];
  962. if (firstC > firstX)
  963. ++shift;
  964. }
  965. if (shift < 2)
  966. {
  967. ShiftRightOneInPlace(cStart, c);
  968. --cBitLength;
  969. ShiftRightOneInPlace(iCountStart, iCount);
  970. }
  971. else
  972. {
  973. ShiftRightInPlace(cStart, c, shift);
  974. cBitLength -= shift;
  975. ShiftRightInPlace(iCountStart, iCount, shift);
  976. }
  977. //cStart = c.Length - ((cBitLength + 31) / 32);
  978. while (c[cStart] == 0)
  979. {
  980. ++cStart;
  981. }
  982. while (iCount[iCountStart] == 0)
  983. {
  984. ++iCountStart;
  985. }
  986. }
  987. }
  988. else
  989. {
  990. count = new int[1];
  991. }
  992. if (xyCmp == 0)
  993. {
  994. AddMagnitudes(count, One.magnitude);
  995. Array.Clear(x, xStart, x.Length - xStart);
  996. }
  997. return count;
  998. }
  999. public BigInteger Divide(
  1000. BigInteger val)
  1001. {
  1002. if (val.sign == 0)
  1003. throw new ArithmeticException("Division by zero error");
  1004. if (sign == 0)
  1005. return Zero;
  1006. if (val.QuickPow2Check()) // val is power of two
  1007. {
  1008. BigInteger result = this.Abs().ShiftRight(val.Abs().BitLength - 1);
  1009. return val.sign == this.sign ? result : result.Negate();
  1010. }
  1011. int[] mag = (int[]) this.magnitude.Clone();
  1012. return new BigInteger(this.sign * val.sign, Divide(mag, val.magnitude), true);
  1013. }
  1014. public BigInteger[] DivideAndRemainder(
  1015. BigInteger val)
  1016. {
  1017. if (val.sign == 0)
  1018. throw new ArithmeticException("Division by zero error");
  1019. BigInteger[] biggies = new BigInteger[2];
  1020. if (sign == 0)
  1021. {
  1022. biggies[0] = Zero;
  1023. biggies[1] = Zero;
  1024. }
  1025. else if (val.QuickPow2Check()) // val is power of two
  1026. {
  1027. int e = val.Abs().BitLength - 1;
  1028. BigInteger quotient = this.Abs().ShiftRight(e);
  1029. int[] remainder = this.LastNBits(e);
  1030. biggies[0] = val.sign == this.sign ? quotient : quotient.Negate();
  1031. biggies[1] = new BigInteger(this.sign, remainder, true);
  1032. }
  1033. else
  1034. {
  1035. int[] remainder = (int[]) this.magnitude.Clone();
  1036. int[] quotient = Divide(remainder, val.magnitude);
  1037. biggies[0] = new BigInteger(this.sign * val.sign, quotient, true);
  1038. biggies[1] = new BigInteger(this.sign, remainder, true);
  1039. }
  1040. return biggies;
  1041. }
  1042. public override bool Equals(
  1043. object obj)
  1044. {
  1045. if (obj == this)
  1046. return true;
  1047. BigInteger biggie = obj as BigInteger;
  1048. if (biggie == null)
  1049. return false;
  1050. return sign == biggie.sign && IsEqualMagnitude(biggie);
  1051. }
  1052. private bool IsEqualMagnitude(BigInteger x)
  1053. {
  1054. //int[] xMag = x.magnitude;
  1055. if (magnitude.Length != x.magnitude.Length)
  1056. return false;
  1057. for (int i = 0; i < magnitude.Length; i++)
  1058. {
  1059. if (magnitude[i] != x.magnitude[i])
  1060. return false;
  1061. }
  1062. return true;
  1063. }
  1064. public BigInteger Gcd(
  1065. BigInteger value)
  1066. {
  1067. if (value.sign == 0)
  1068. return Abs();
  1069. if (sign == 0)
  1070. return value.Abs();
  1071. BigInteger r;
  1072. BigInteger u = this;
  1073. BigInteger v = value;
  1074. while (v.sign != 0)
  1075. {
  1076. r = u.Mod(v);
  1077. u = v;
  1078. v = r;
  1079. }
  1080. return u;
  1081. }
  1082. public override int GetHashCode()
  1083. {
  1084. int hc = magnitude.Length;
  1085. if (magnitude.Length > 0)
  1086. {
  1087. hc ^= magnitude[0];
  1088. if (magnitude.Length > 1)
  1089. {
  1090. hc ^= magnitude[magnitude.Length - 1];
  1091. }
  1092. }
  1093. return sign < 0 ? ~hc : hc;
  1094. }
  1095. // TODO Make public?
  1096. private BigInteger Inc()
  1097. {
  1098. if (this.sign == 0)
  1099. return One;
  1100. if (this.sign < 0)
  1101. return new BigInteger(-1, doSubBigLil(this.magnitude, One.magnitude), true);
  1102. return AddToMagnitude(One.magnitude);
  1103. }
  1104. public int IntValue
  1105. {
  1106. get
  1107. {
  1108. if (sign == 0)
  1109. return 0;
  1110. int n = magnitude.Length;
  1111. int v = magnitude[n - 1];
  1112. return sign < 0 ? -v : v;
  1113. }
  1114. }
  1115. /**
  1116. * return whether or not a BigInteger is probably prime with a
  1117. * probability of 1 - (1/2)**certainty.
  1118. * <p>From Knuth Vol 2, pg 395.</p>
  1119. */
  1120. public bool IsProbablePrime(int certainty)
  1121. {
  1122. return IsProbablePrime(certainty, false);
  1123. }
  1124. internal bool IsProbablePrime(int certainty, bool randomlySelected)
  1125. {
  1126. if (certainty <= 0)
  1127. return true;
  1128. BigInteger n = Abs();
  1129. if (!n.TestBit(0))
  1130. return n.Equals(Two);
  1131. if (n.Equals(One))
  1132. return false;
  1133. return n.CheckProbablePrime(certainty, RandomSource, randomlySelected);
  1134. }
  1135. private bool CheckProbablePrime(int certainty, Random random, bool randomlySelected)
  1136. {
  1137. Debug.Assert(certainty > 0);
  1138. Debug.Assert(CompareTo(Two) > 0);
  1139. Debug.Assert(TestBit(0));
  1140. // Try to reduce the penalty for really small numbers
  1141. int numLists = System.Math.Min(BitLength - 1, primeLists.Length);
  1142. for (int i = 0; i < numLists; ++i)
  1143. {
  1144. int test = Remainder(primeProducts[i]);
  1145. int[] primeList = primeLists[i];
  1146. for (int j = 0; j < primeList.Length; ++j)
  1147. {
  1148. int prime = primeList[j];
  1149. int qRem = test % prime;
  1150. if (qRem == 0)
  1151. {
  1152. // We may find small numbers in the list
  1153. return BitLength < 16 && IntValue == prime;
  1154. }
  1155. }
  1156. }
  1157. // TODO Special case for < 10^16 (RabinMiller fixed list)
  1158. // if (BitLength < 30)
  1159. // {
  1160. // RabinMiller against 2, 3, 5, 7, 11, 13, 23 is sufficient
  1161. // }
  1162. // TODO Is it worth trying to create a hybrid of these two?
  1163. return RabinMillerTest(certainty, random, randomlySelected);
  1164. // return SolovayStrassenTest(certainty, random);
  1165. // bool rbTest = RabinMillerTest(certainty, random);
  1166. // bool ssTest = SolovayStrassenTest(certainty, random);
  1167. //
  1168. // Debug.Assert(rbTest == ssTest);
  1169. //
  1170. // return rbTest;
  1171. }
  1172. public bool RabinMillerTest(int certainty, Random random)
  1173. {
  1174. return RabinMillerTest(certainty, random, false);
  1175. }
  1176. internal bool RabinMillerTest(int certainty, Random random, bool randomlySelected)
  1177. {
  1178. int bits = BitLength;
  1179. Debug.Assert(certainty > 0);
  1180. Debug.Assert(bits > 2);
  1181. Debug.Assert(TestBit(0));
  1182. int iterations = ((certainty - 1) / 2) + 1;
  1183. if (randomlySelected)
  1184. {
  1185. int itersFor100Cert = bits >= 1024 ? 4
  1186. : bits >= 512 ? 8
  1187. : bits >= 256 ? 16
  1188. : 50;
  1189. if (certainty < 100)
  1190. {
  1191. iterations = System.Math.Min(itersFor100Cert, iterations);
  1192. }
  1193. else
  1194. {
  1195. iterations -= 50;
  1196. iterations += itersFor100Cert;
  1197. }
  1198. }
  1199. // let n = 1 + d . 2^s
  1200. BigInteger n = this;
  1201. int s = n.GetLowestSetBitMaskFirst(-1 << 1);
  1202. Debug.Assert(s >= 1);
  1203. BigInteger r = n.ShiftRight(s);
  1204. // NOTE: Avoid conversion to/from Montgomery form and check for R/-R as result instead
  1205. BigInteger montRadix = One.ShiftLeft(32 * n.magnitude.Length).Remainder(n);
  1206. BigInteger minusMontRadix = n.Subtract(montRadix);
  1207. do
  1208. {
  1209. BigInteger a;
  1210. do
  1211. {
  1212. a = new BigInteger(n.BitLength, random);
  1213. }
  1214. while (a.sign == 0 || a.CompareTo(n) >= 0
  1215. || a.IsEqualMagnitude(montRadix) || a.IsEqualMagnitude(minusMontRadix));
  1216. BigInteger y = ModPowMonty(a, r, n, false);
  1217. if (!y.Equals(montRadix))
  1218. {
  1219. int j = 0;
  1220. while (!y.Equals(minusMontRadix))
  1221. {
  1222. if (++j == s)
  1223. return false;
  1224. y = ModPowMonty(y, Two, n, false);
  1225. if (y.Equals(montRadix))
  1226. return false;
  1227. }
  1228. }
  1229. }
  1230. while (--iterations > 0);
  1231. return true;
  1232. }
  1233. // private bool SolovayStrassenTest(
  1234. // int certainty,
  1235. // Random random)
  1236. // {
  1237. // Debug.Assert(certainty > 0);
  1238. // Debug.Assert(CompareTo(Two) > 0);
  1239. // Debug.Assert(TestBit(0));
  1240. //
  1241. // BigInteger n = this;
  1242. // BigInteger nMinusOne = n.Subtract(One);
  1243. // BigInteger e = nMinusOne.ShiftRight(1);
  1244. //
  1245. // do
  1246. // {
  1247. // BigInteger a;
  1248. // do
  1249. // {
  1250. // a = new BigInteger(nBitLength, random);
  1251. // }
  1252. // // NB: Spec says 0 < x < n, but 1 is trivial
  1253. // while (a.CompareTo(One) <= 0 || a.CompareTo(n) >= 0);
  1254. //
  1255. //
  1256. // // TODO Check this is redundant given the way Jacobi() works?
  1257. //// if (!a.Gcd(n).Equals(One))
  1258. //// return false;
  1259. //
  1260. // int x = Jacobi(a, n);
  1261. //
  1262. // if (x == 0)
  1263. // return false;
  1264. //
  1265. // BigInteger check = a.ModPow(e, n);
  1266. //
  1267. // if (x == 1 && !check.Equals(One))
  1268. // return false;
  1269. //
  1270. // if (x == -1 && !check.Equals(nMinusOne))
  1271. // return false;
  1272. //
  1273. // --certainty;
  1274. // }
  1275. // while (certainty > 0);
  1276. //
  1277. // return true;
  1278. // }
  1279. //
  1280. // private static int Jacobi(
  1281. // BigInteger a,
  1282. // BigInteger b)
  1283. // {
  1284. // Debug.Assert(a.sign >= 0);
  1285. // Debug.Assert(b.sign > 0);
  1286. // Debug.Assert(b.TestBit(0));
  1287. // Debug.Assert(a.CompareTo(b) < 0);
  1288. //
  1289. // int totalS = 1;
  1290. // for (;;)
  1291. // {
  1292. // if (a.sign == 0)
  1293. // return 0;
  1294. //
  1295. // if (a.Equals(One))
  1296. // break;
  1297. //
  1298. // int e = a.GetLowestSetBit();
  1299. //
  1300. // int bLsw = b.magnitude[b.magnitude.Length - 1];
  1301. // if ((e & 1) != 0 && ((bLsw & 7) == 3 || (bLsw & 7) == 5))
  1302. // totalS = -totalS;
  1303. //
  1304. // // TODO Confirm this is faster than later a1.Equals(One) test
  1305. // if (a.BitLength == e + 1)
  1306. // break;
  1307. // BigInteger a1 = a.ShiftRight(e);
  1308. //// if (a1.Equals(One))
  1309. //// break;
  1310. //
  1311. // int a1Lsw = a1.magnitude[a1.magnitude.Length - 1];
  1312. // if ((bLsw & 3) == 3 && (a1Lsw & 3) == 3)
  1313. // totalS = -totalS;
  1314. //
  1315. //// a = b.Mod(a1);
  1316. // a = b.Remainder(a1);
  1317. // b = a1;
  1318. // }
  1319. // return totalS;
  1320. // }
  1321. public long LongValue
  1322. {
  1323. get
  1324. {
  1325. if (sign == 0)
  1326. return 0;
  1327. int n = magnitude.Length;
  1328. long v = magnitude[n - 1] & IMASK;
  1329. if (n > 1)
  1330. {
  1331. v |= (magnitude[n - 2] & IMASK) << 32;
  1332. }
  1333. return sign < 0 ? -v : v;
  1334. }
  1335. }
  1336. public BigInteger Max(
  1337. BigInteger value)
  1338. {
  1339. return CompareTo(value) > 0 ? this : value;
  1340. }
  1341. public BigInteger Min(
  1342. BigInteger value)
  1343. {
  1344. return CompareTo(value) < 0 ? this : value;
  1345. }
  1346. public BigInteger Mod(
  1347. BigInteger m)
  1348. {
  1349. if (m.sign < 1)
  1350. throw new ArithmeticException("Modulus must be positive");
  1351. BigInteger biggie = Remainder(m);
  1352. return (biggie.sign >= 0 ? biggie : biggie.Add(m));
  1353. }
  1354. public BigInteger ModInverse(
  1355. BigInteger m)
  1356. {
  1357. if (m.sign < 1)
  1358. throw new ArithmeticException("Modulus must be positive");
  1359. // TODO Too slow at the moment
  1360. // // "Fast Key Exchange with Elliptic Curve Systems" R.Schoeppel
  1361. // if (m.TestBit(0))
  1362. // {
  1363. // //The Almost Inverse Algorithm
  1364. // int k = 0;
  1365. // BigInteger B = One, C = Zero, F = this, G = m, tmp;
  1366. //
  1367. // for (;;)
  1368. // {
  1369. // // While F is even, do F=F/u, C=C*u, k=k+1.
  1370. // int zeroes = F.GetLowestSetBit();
  1371. // if (zeroes > 0)
  1372. // {
  1373. // F = F.ShiftRight(zeroes);
  1374. // C = C.ShiftLeft(zeroes);
  1375. // k += zeroes;
  1376. // }
  1377. //
  1378. // // If F = 1, then return B,k.
  1379. // if (F.Equals(One))
  1380. // {
  1381. // BigInteger half = m.Add(One).ShiftRight(1);
  1382. // BigInteger halfK = half.ModPow(BigInteger.ValueOf(k), m);
  1383. // return B.Multiply(halfK).Mod(m);
  1384. // }
  1385. //
  1386. // if (F.CompareTo(G) < 0)
  1387. // {
  1388. // tmp = G; G = F; F = tmp;
  1389. // tmp = B; B = C; C = tmp;
  1390. // }
  1391. //
  1392. // F = F.Add(G);
  1393. // B = B.Add(C);
  1394. // }
  1395. // }
  1396. if (m.QuickPow2Check())
  1397. {
  1398. return ModInversePow2(m);
  1399. }
  1400. BigInteger d = this.Remainder(m);
  1401. BigInteger x;
  1402. BigInteger gcd = ExtEuclid(d, m, out x);
  1403. if (!gcd.Equals(One))
  1404. throw new ArithmeticException("Numbers not relatively prime.");
  1405. if (x.sign < 0)
  1406. {
  1407. x = x.Add(m);
  1408. }
  1409. return x;
  1410. }
  1411. private BigInteger ModInversePow2(BigInteger m)
  1412. {
  1413. Debug.Assert(m.SignValue > 0);
  1414. Debug.Assert(m.BitCount == 1);
  1415. if (!TestBit(0))
  1416. {
  1417. throw new ArithmeticException("Numbers not relatively prime.");
  1418. }
  1419. int pow = m.BitLength - 1;
  1420. long inv64 = ModInverse64(LongValue);
  1421. if (pow < 64)
  1422. {
  1423. inv64 &= ((1L << pow) - 1);
  1424. }
  1425. BigInteger x = BigInteger.ValueOf(inv64);
  1426. if (pow > 64)
  1427. {
  1428. BigInteger d = this.Remainder(m);
  1429. int bitsCorrect = 64;
  1430. do
  1431. {
  1432. BigInteger t = x.Multiply(d).Remainder(m);
  1433. x = x.Multiply(Two.Subtract(t)).Remainder(m);
  1434. bitsCorrect <<= 1;
  1435. }
  1436. while (bitsCorrect < pow);
  1437. }
  1438. if (x.sign < 0)
  1439. {
  1440. x = x.Add(m);
  1441. }
  1442. return x;
  1443. }
  1444. private static int ModInverse32(int d)
  1445. {
  1446. // Newton's method with initial estimate "correct to 4 bits"
  1447. Debug.Assert((d & 1) != 0);
  1448. int x = d + (((d + 1) & 4) << 1); // d.x == 1 mod 2**4
  1449. Debug.Assert(((d * x) & 15) == 1);
  1450. x *= 2 - d * x; // d.x == 1 mod 2**8
  1451. x *= 2 - d * x; // d.x == 1 mod 2**16
  1452. x *= 2 - d * x; // d.x == 1 mod 2**32
  1453. Debug.Assert(d * x == 1);
  1454. return x;
  1455. }
  1456. private static long ModInverse64(long d)
  1457. {
  1458. // Newton's method with initial estimate "correct to 4 bits"
  1459. Debug.Assert((d & 1L) != 0);
  1460. long x = d + (((d + 1L) & 4L) << 1); // d.x == 1 mod 2**4
  1461. Debug.Assert(((d * x) & 15L) == 1L);
  1462. x *= 2 - d * x; // d.x == 1 mod 2**8
  1463. x *= 2 - d * x; // d.x == 1 mod 2**16
  1464. x *= 2 - d * x; // d.x == 1 mod 2**32
  1465. x *= 2 - d * x; // d.x == 1 mod 2**64
  1466. Debug.Assert(d * x == 1L);
  1467. return x;
  1468. }
  1469. /**
  1470. * Calculate the numbers u1, u2, and u3 such that:
  1471. *
  1472. * u1 * a + u2 * b = u3
  1473. *
  1474. * where u3 is the greatest common divider of a and b.
  1475. * a and b using the extended Euclid algorithm (refer p. 323
  1476. * of The Art of Computer Programming vol 2, 2nd ed).
  1477. * This also seems to have the side effect of calculating
  1478. * some form of multiplicative inverse.
  1479. *
  1480. * @param a First number to calculate gcd for
  1481. * @param b Second number to calculate gcd for
  1482. * @param u1Out the return object for the u1 value
  1483. * @return The greatest common divisor of a and b
  1484. */
  1485. private static BigInteger ExtEuclid(BigInteger a, BigInteger b, out BigInteger u1Out)
  1486. {
  1487. BigInteger u1 = One, v1 = Zero;
  1488. BigInteger u3 = a, v3 = b;
  1489. if (v3.sign > 0)
  1490. {
  1491. for (;;)
  1492. {
  1493. BigInteger[] q = u3.DivideAndRemainder(v3);
  1494. u3 = v3;
  1495. v3 = q[1];
  1496. BigInteger oldU1 = u1;
  1497. u1 = v1;
  1498. if (v3.sign <= 0)
  1499. break;
  1500. v1 = oldU1.Subtract(v1.Multiply(q[0]));
  1501. }
  1502. }
  1503. u1Out = u1;
  1504. return u3;
  1505. }
  1506. private static void ZeroOut(
  1507. int[] x)
  1508. {
  1509. Array.Clear(x, 0, x.Length);
  1510. }
  1511. public BigInteger ModPow(BigInteger e, BigInteger m)
  1512. {
  1513. if (m.sign < 1)
  1514. throw new ArithmeticException("Modulus must be positive");
  1515. if (m.Equals(One))
  1516. return Zero;
  1517. if (e.sign == 0)
  1518. return One;
  1519. if (sign == 0)
  1520. return Zero;
  1521. bool negExp = e.sign < 0;
  1522. if (negExp)
  1523. e = e.Negate();
  1524. BigInteger result = this.Mod(m);
  1525. if (!e.Equals(One))
  1526. {
  1527. if ((m.magnitude[m.magnitude.Length - 1] & 1) == 0)
  1528. {
  1529. result = ModPowBarrett(result, e, m);
  1530. }
  1531. else
  1532. {
  1533. result = ModPowMonty(result, e, m, true);
  1534. }
  1535. }
  1536. if (negExp)
  1537. result = result.ModInverse(m);
  1538. return result;
  1539. }
  1540. private static BigInteger ModPowBarrett(BigInteger b, BigInteger e, BigInteger m)
  1541. {
  1542. int k = m.magnitude.Length;
  1543. BigInteger mr = One.ShiftLeft((k + 1) << 5);
  1544. BigInteger yu = One.ShiftLeft(k << 6).Divide(m);
  1545. // Sliding window from MSW to LSW
  1546. int extraBits = 0, expLength = e.BitLength;
  1547. while (expLength > ExpWindowThresholds[extraBits])
  1548. {
  1549. ++extraBits;
  1550. }
  1551. int numPowers = 1 << extraBits;
  1552. BigInteger[] oddPowers = new BigInteger[numPowers];
  1553. oddPowers[0] = b;
  1554. BigInteger b2 = ReduceBarrett(b.Square(), m, mr, yu);
  1555. for (int i = 1; i < numPowers; ++i)
  1556. {
  1557. oddPowers[i] = ReduceBarrett(oddPowers[i - 1].Multiply(b2), m, mr, yu);
  1558. }
  1559. int[] windowList = GetWindowList(e.magnitude, extraBits);
  1560. Debug.Assert(windowList.Length > 0);
  1561. int window = windowList[0];
  1562. int mult = window & 0xFF, lastZeroes = window >> 8;
  1563. BigInteger y;
  1564. if (mult == 1)
  1565. {
  1566. y = b2;
  1567. --lastZeroes;
  1568. }
  1569. else
  1570. {
  1571. y = oddPowers[mult >> 1];
  1572. }
  1573. int windowPos = 1;
  1574. while ((window = windowList[windowPos++]) != -1)
  1575. {
  1576. mult = window & 0xFF;
  1577. int bits = lastZeroes + BitLengthTable[mult];
  1578. for (int j = 0; j < bits; ++j)
  1579. {
  1580. y = ReduceBarrett(y.Square(), m, mr, yu);
  1581. }
  1582. y = ReduceBarrett(y.Multiply(oddPowers[mult >> 1]), m, mr, yu);
  1583. lastZeroes = window >> 8;
  1584. }
  1585. for (int i = 0; i < lastZeroes; ++i)
  1586. {
  1587. y = ReduceBarrett(y.Square(), m, mr, yu);
  1588. }
  1589. return y;
  1590. }
  1591. private static BigInteger ReduceBarrett(BigInteger x, BigInteger m, BigInteger mr, BigInteger yu)
  1592. {
  1593. int xLen = x.BitLength, mLen = m.BitLength;
  1594. if (xLen < mLen)
  1595. return x;
  1596. if (xLen - mLen > 1)
  1597. {
  1598. int k = m.magnitude.Length;
  1599. BigInteger q1 = x.DivideWords(k - 1);
  1600. BigInteger q2 = q1.Multiply(yu); // TODO Only need partial multiplication here
  1601. BigInteger q3 = q2.DivideWords(k + 1);
  1602. BigInteger r1 = x.RemainderWords(k + 1);
  1603. BigInteger r2 = q3.Multiply(m); // TODO Only need partial multiplication here
  1604. BigInteger r3 = r2.RemainderWords(k + 1);
  1605. x = r1.Subtract(r3);
  1606. if (x.sign < 0)
  1607. {
  1608. x = x.Add(mr);
  1609. }
  1610. }
  1611. while (x.CompareTo(m) >= 0)
  1612. {
  1613. x = x.Subtract(m);
  1614. }
  1615. return x;
  1616. }
  1617. private static BigInteger ModPowMonty(BigInteger b, BigInteger e, BigInteger m, bool convert)
  1618. {
  1619. int n = m.magnitude.Length;
  1620. int powR = 32 * n;
  1621. bool smallMontyModulus = m.BitLength + 2 <= powR;
  1622. uint mDash = (uint)m.GetMQuote();
  1623. // tmp = this * R mod m
  1624. if (convert)
  1625. {
  1626. b = b.ShiftLeft(powR).Remainder(m);
  1627. }
  1628. int[] yAccum = new int[n + 1];
  1629. int[] zVal = b.magnitude;
  1630. Debug.Assert(zVal.Length <= n);
  1631. if (zVal.Length < n)
  1632. {
  1633. int[] tmp = new int[n];
  1634. zVal.CopyTo(tmp, n - zVal.Length);
  1635. zVal = tmp;
  1636. }
  1637. // Sliding window from MSW to LSW
  1638. int extraBits = 0;
  1639. // Filter the common case of small RSA exponents with few bits set
  1640. if (e.magnitude.Length > 1 || e.BitCount > 2)
  1641. {
  1642. int expLength = e.BitLength;
  1643. while (expLength > ExpWindowThresholds[extraBits])
  1644. {
  1645. ++extraBits;
  1646. }
  1647. }
  1648. int numPowers = 1 << extraBits;
  1649. int[][] oddPowers = new int[numPowers][];
  1650. oddPowers[0] = zVal;
  1651. int[] zSquared = Arrays.Clone(zVal);
  1652. SquareMonty(yAccum, zSquared, m.magnitude, mDash, smallMontyModulus);
  1653. for (int i = 1; i < numPowers; ++i)
  1654. {
  1655. oddPowers[i] = Arrays.Clone(oddPowers[i - 1]);
  1656. MultiplyMonty(yAccum, oddPowers[i], zSquared, m.magnitude, mDash, smallMontyModulus);
  1657. }
  1658. int[] windowList = GetWindowList(e.magnitude, extraBits);
  1659. Debug.Assert(windowList.Length > 1);
  1660. int window = windowList[0];
  1661. int mult = window & 0xFF, lastZeroes = window >> 8;
  1662. int[] yVal;
  1663. if (mult == 1)
  1664. {
  1665. yVal = zSquared;
  1666. --lastZeroes;
  1667. }
  1668. else
  1669. {
  1670. yVal = Arrays.Clone(oddPowers[mult >> 1]);
  1671. }
  1672. int windowPos = 1;
  1673. while ((window = windowList[windowPos++]) != -1)
  1674. {
  1675. mult = window & 0xFF;
  1676. int bits = lastZeroes + BitLengthTable[mult];
  1677. for (int j = 0; j < bits; ++j)
  1678. {
  1679. SquareMonty(yAccum, yVal, m.magnitude, mDash, smallMontyModulus);
  1680. }
  1681. MultiplyMonty(yAccum, yVal, oddPowers[mult >> 1], m.magnitude, mDash, smallMontyModulus);
  1682. lastZeroes = window >> 8;
  1683. }
  1684. for (int i = 0; i < lastZeroes; ++i)
  1685. {
  1686. SquareMonty(yAccum, yVal, m.magnitude, mDash, smallMontyModulus);
  1687. }
  1688. if (convert)
  1689. {
  1690. // Return y * R^(-1) mod m
  1691. MontgomeryReduce(yVal, m.magnitude, mDash);
  1692. }
  1693. else if (smallMontyModulus && CompareTo(0, yVal, 0, m.magnitude) >= 0)
  1694. {
  1695. Subtract(0, yVal, 0, m.magnitude);
  1696. }
  1697. return new BigInteger(1, yVal, true);
  1698. }
  1699. private static int[] GetWindowList(int[] mag, int extraBits)
  1700. {
  1701. int v = mag[0];
  1702. Debug.Assert(v != 0);
  1703. int leadingBits = BitLen(v);
  1704. int resultSize = (((mag.Length - 1) << 5) + leadingBits) / (1 + extraBits) + 2;
  1705. int[] result = new int[resultSize];
  1706. int resultPos = 0;
  1707. int bitPos = 33 - leadingBits;
  1708. v <<= bitPos;
  1709. int mult = 1, multLimit = 1 << extraBits;
  1710. int zeroes = 0;
  1711. int i = 0;
  1712. for (; ; )
  1713. {
  1714. for (; bitPos < 32; ++bitPos)
  1715. {
  1716. if (mult < multLimit)
  1717. {
  1718. mult = (mult << 1) | (int)((uint)v >> 31);
  1719. }
  1720. else if (v < 0)
  1721. {
  1722. result[resultPos++] = CreateWindowEntry(mult, zeroes);
  1723. mult = 1;
  1724. zeroes = 0;
  1725. }
  1726. else
  1727. {
  1728. ++zeroes;
  1729. }
  1730. v <<= 1;
  1731. }
  1732. if (++i == mag.Length)
  1733. {
  1734. result[resultPos++] = CreateWindowEntry(mult, zeroes);
  1735. break;
  1736. }
  1737. v = mag[i];
  1738. bitPos = 0;
  1739. }
  1740. result[resultPos] = -1;
  1741. return result;
  1742. }
  1743. private static int CreateWindowEntry(int mult, int zeroes)
  1744. {
  1745. while ((mult & 1) == 0)
  1746. {
  1747. mult >>= 1;
  1748. ++zeroes;
  1749. }
  1750. return mult | (zeroes << 8);
  1751. }
  1752. /**
  1753. * return w with w = x * x - w is assumed to have enough space.
  1754. */
  1755. private static int[] Square(
  1756. int[] w,
  1757. int[] x)
  1758. {
  1759. // Note: this method allows w to be only (2 * x.Length - 1) words if result will fit
  1760. // if (w.Length != 2 * x.Length)
  1761. // throw new ArgumentException("no I don't think so...");
  1762. ulong c;
  1763. int wBase = w.Length - 1;
  1764. for (int i = x.Length - 1; i > 0; --i)
  1765. {
  1766. ulong v = (uint)x[i];
  1767. c = v * v + (uint)w[wBase];
  1768. w[wBase] = (int)c;
  1769. c >>= 32;
  1770. for (int j = i - 1; j >= 0; --j)
  1771. {
  1772. ulong prod = v * (uint)x[j];
  1773. c += ((uint)w[--wBase] & UIMASK) + ((uint)prod << 1);
  1774. w[wBase] = (int)c;
  1775. c = (c >> 32) + (prod >> 31);
  1776. }
  1777. c += (uint)w[--wBase];
  1778. w[wBase] = (int)c;
  1779. if (--wBase >= 0)
  1780. {
  1781. w[wBase] = (int)(c >> 32);
  1782. }
  1783. else
  1784. {
  1785. Debug.Assert((c >> 32) == 0);
  1786. }
  1787. wBase += i;
  1788. }
  1789. c = (uint)x[0];
  1790. c = c * c + (uint)w[wBase];
  1791. w[wBase] = (int)c;
  1792. if (--wBase >= 0)
  1793. {
  1794. w[wBase] += (int)(c >> 32);
  1795. }
  1796. else
  1797. {
  1798. Debug.Assert((c >> 32) == 0);
  1799. }
  1800. return w;
  1801. }
  1802. /**
  1803. * return x with x = y * z - x is assumed to have enough space.
  1804. */
  1805. private static int[] Multiply(int[] x, int[] y, int[] z)
  1806. {
  1807. int i = z.Length;
  1808. if (i < 1)
  1809. return x;
  1810. int xBase = x.Length - y.Length;
  1811. do
  1812. {
  1813. long a = z[--i] & IMASK;
  1814. long val = 0;
  1815. if (a != 0)
  1816. {
  1817. for (int j = y.Length - 1; j >= 0; j--)
  1818. {
  1819. val += a * (y[j] & IMASK) + (x[xBase + j] & IMASK);
  1820. x[xBase + j] = (int)val;
  1821. val = (long)((ulong)val >> 32);
  1822. }
  1823. }
  1824. --xBase;
  1825. if (xBase >= 0)
  1826. {
  1827. x[xBase] = (int)val;
  1828. }
  1829. else
  1830. {
  1831. Debug.Assert(val == 0);
  1832. }
  1833. }
  1834. while (i > 0);
  1835. return x;
  1836. }
  1837. /**
  1838. * Calculate mQuote = -m^(-1) mod b with b = 2^32 (32 = word size)
  1839. */
  1840. private int GetMQuote()
  1841. {
  1842. if (mQuote != 0)
  1843. {
  1844. return mQuote; // already calculated
  1845. }
  1846. Debug.Assert(this.sign > 0);
  1847. int d = -magnitude[magnitude.Length - 1];
  1848. Debug.Assert((d & 1) != 0);
  1849. return mQuote = ModInverse32(d);
  1850. }
  1851. private static void MontgomeryReduce(int[] x, int[] m, uint mDash) // mDash = -m^(-1) mod b
  1852. {
  1853. // NOTE: Not a general purpose reduction (which would allow x up to twice the bitlength of m)
  1854. Debug.Assert(x.Length == m.Length);
  1855. int n = m.Length;
  1856. for (int i = n - 1; i >= 0; --i)
  1857. {
  1858. uint x0 = (uint)x[n - 1];
  1859. ulong t = x0 * mDash;
  1860. ulong carry = t * (uint)m[n - 1] + x0;
  1861. Debug.Assert((uint)carry == 0);
  1862. carry >>= 32;
  1863. for (int j = n - 2; j >= 0; --j)
  1864. {
  1865. carry += t * (uint)m[j] + (uint)x[j];
  1866. x[j + 1] = (int)carry;
  1867. carry >>= 32;
  1868. }
  1869. x[0] = (int)carry;
  1870. Debug.Assert(carry >> 32 == 0);
  1871. }
  1872. if (CompareTo(0, x, 0, m) >= 0)
  1873. {
  1874. Subtract(0, x, 0, m);
  1875. }
  1876. }
  1877. /**
  1878. * Montgomery multiplication: a = x * y * R^(-1) mod m
  1879. * <br/>
  1880. * Based algorithm 14.36 of Handbook of Applied Cryptography.
  1881. * <br/>
  1882. * <li> m, x, y should have length n </li>
  1883. * <li> a should have length (n + 1) </li>
  1884. * <li> b = 2^32, R = b^n </li>
  1885. * <br/>
  1886. * The result is put in x
  1887. * <br/>
  1888. * NOTE: the indices of x, y, m, a different in HAC and in Java
  1889. */
  1890. private static void MultiplyMonty(int[] a, int[] x, int[] y, int[] m, uint mDash, bool smallMontyModulus)
  1891. // mDash = -m^(-1) mod b
  1892. {
  1893. int n = m.Length;
  1894. if (n == 1)
  1895. {
  1896. x[0] = (int)MultiplyMontyNIsOne((uint)x[0], (uint)y[0], (uint)m[0], mDash);
  1897. return;
  1898. }
  1899. uint y0 = (uint)y[n - 1];
  1900. int aMax;
  1901. {
  1902. ulong xi = (uint)x[n - 1];
  1903. ulong carry = xi * y0;
  1904. ulong t = (uint)carry * mDash;
  1905. ulong prod2 = t * (uint)m[n - 1];
  1906. carry += (uint)prod2;
  1907. Debug.Assert((uint)carry == 0);
  1908. carry = (carry >> 32) + (prod2 >> 32);
  1909. for (int j = n - 2; j >= 0; --j)
  1910. {
  1911. ulong prod1 = xi * (uint)y[j];
  1912. prod2 = t * (uint)m[j];
  1913. carry += (prod1 & UIMASK) + (uint)prod2;
  1914. a[j + 2] = (int)carry;
  1915. carry = (carry >> 32) + (prod1 >> 32) + (prod2 >> 32);
  1916. }
  1917. a[1] = (int)carry;
  1918. aMax = (int)(carry >> 32);
  1919. }
  1920. for (int i = n - 2; i >= 0; --i)
  1921. {
  1922. uint a0 = (uint)a[n];
  1923. ulong xi = (uint)x[i];
  1924. ulong prod1 = xi * y0;
  1925. ulong carry = (prod1 & UIMASK) + a0;
  1926. ulong t = (uint)carry * mDash;
  1927. ulong prod2 = t * (uint)m[n - 1];
  1928. carry += (uint)prod2;
  1929. Debug.Assert((uint)carry == 0);
  1930. carry = (carry >> 32) + (prod1 >> 32) + (prod2 >> 32);
  1931. for (int j = n - 2; j >= 0; --j)
  1932. {
  1933. prod1 = xi * (uint)y[j];
  1934. prod2 = t * (uint)m[j];
  1935. carry += (prod1 & UIMASK) + (uint)prod2 + (uint)a[j + 1];
  1936. a[j + 2] = (int)carry;
  1937. carry = (carry >> 32) + (prod1 >> 32) + (prod2 >> 32);
  1938. }
  1939. carry += (uint)aMax;
  1940. a[1] = (int)carry;
  1941. aMax = (int)(carry >> 32);
  1942. }
  1943. a[0] = aMax;
  1944. if (!smallMontyModulus && CompareTo(0, a, 0, m) >= 0)
  1945. {
  1946. Subtract(0, a, 0, m);
  1947. }
  1948. Array.Copy(a, 1, x, 0, n);
  1949. }
  1950. private static void SquareMonty(int[] a, int[] x, int[] m, uint mDash, bool smallMontyModulus)
  1951. // mDash = -m^(-1) mod b
  1952. {
  1953. int n = m.Length;
  1954. if (n == 1)
  1955. {
  1956. uint xVal = (uint)x[0];
  1957. x[0] = (int)MultiplyMontyNIsOne(xVal, xVal, (uint)m[0], mDash);
  1958. return;
  1959. }
  1960. ulong x0 = (uint)x[n - 1];
  1961. int aMax;
  1962. {
  1963. ulong carry = x0 * x0;
  1964. ulong t = (uint)carry * mDash;
  1965. ulong prod2 = t * (uint)m[n - 1];
  1966. carry += (uint)prod2;
  1967. Debug.Assert((uint)carry == 0);
  1968. carry = (carry >> 32) + (prod2 >> 32);
  1969. for (int j = n - 2; j >= 0; --j)
  1970. {
  1971. ulong prod1 = x0 * (uint)x[j];
  1972. prod2 = t * (uint)m[j];
  1973. carry += (prod2 & UIMASK) + ((uint)prod1 << 1);
  1974. a[j + 2] = (int)carry;
  1975. carry = (carry >> 32) + (prod1 >> 31) + (prod2 >> 32);
  1976. }
  1977. a[1] = (int)carry;
  1978. aMax = (int)(carry >> 32);
  1979. }
  1980. for (int i = n - 2; i >= 0; --i)
  1981. {
  1982. uint a0 = (uint)a[n];
  1983. ulong t = a0 * mDash;
  1984. ulong carry = t * (uint)m[n - 1] + a0;
  1985. Debug.Assert((uint)carry == 0);
  1986. carry >>= 32;
  1987. for (int j = n - 2; j > i; --j)
  1988. {
  1989. carry += t * (uint)m[j] + (uint)a[j + 1];
  1990. a[j + 2] = (int)carry;
  1991. carry >>= 32;
  1992. }
  1993. ulong xi = (uint)x[i];
  1994. {
  1995. ulong prod1 = xi * xi;
  1996. ulong prod2 = t * (uint)m[i];
  1997. carry += (prod1 & UIMASK) + (uint)prod2 + (uint)a[i + 1];
  1998. a[i + 2] = (int)carry;
  1999. carry = (carry >> 32) + (prod1 >> 32) + (prod2 >> 32);
  2000. }
  2001. for (int j = i - 1; j >= 0; --j)
  2002. {
  2003. ulong prod1 = xi * (uint)x[j];
  2004. ulong prod2 = t * (uint)m[j];
  2005. carry += (prod2 & UIMASK) + ((uint)prod1 << 1) + (uint)a[j + 1];
  2006. a[j + 2] = (int)carry;
  2007. carry = (carry >> 32) + (prod1 >> 31) + (prod2 >> 32);
  2008. }
  2009. carry += (uint)aMax;
  2010. a[1] = (int)carry;
  2011. aMax = (int)(carry >> 32);
  2012. }
  2013. a[0] = aMax;
  2014. if (!smallMontyModulus && CompareTo(0, a, 0, m) >= 0)
  2015. {
  2016. Subtract(0, a, 0, m);
  2017. }
  2018. Array.Copy(a, 1, x, 0, n);
  2019. }
  2020. private static uint MultiplyMontyNIsOne(uint x, uint y, uint m, uint mDash)
  2021. {
  2022. ulong carry = (ulong)x * y;
  2023. uint t = (uint)carry * mDash;
  2024. ulong um = m;
  2025. ulong prod2 = um * t;
  2026. carry += (uint)prod2;
  2027. Debug.Assert((uint)carry == 0);
  2028. carry = (carry >> 32) + (prod2 >> 32);
  2029. if (carry > um)
  2030. {
  2031. carry -= um;
  2032. }
  2033. Debug.Assert(carry < um);
  2034. return (uint)carry;
  2035. }
  2036. public BigInteger Multiply(
  2037. BigInteger val)
  2038. {
  2039. if (val == this)
  2040. return Square();
  2041. if ((sign & val.sign) == 0)
  2042. return Zero;
  2043. if (val.QuickPow2Check()) // val is power of two
  2044. {
  2045. BigInteger result = this.ShiftLeft(val.Abs().BitLength - 1);
  2046. return val.sign > 0 ? result : result.Negate();
  2047. }
  2048. if (this.QuickPow2Check()) // this is power of two
  2049. {
  2050. BigInteger result = val.ShiftLeft(this.Abs().BitLength - 1);
  2051. return this.sign > 0 ? result : result.Negate();
  2052. }
  2053. int resLength = magnitude.Length + val.magnitude.Length;
  2054. int[] res = new int[resLength];
  2055. Multiply(res, this.magnitude, val.magnitude);
  2056. int resSign = sign ^ val.sign ^ 1;
  2057. return new BigInteger(resSign, res, true);
  2058. }
  2059. public BigInteger Square()
  2060. {
  2061. if (sign == 0)
  2062. return Zero;
  2063. if (this.QuickPow2Check())
  2064. return ShiftLeft(Abs().BitLength - 1);
  2065. int resLength = magnitude.Length << 1;
  2066. if ((uint)magnitude[0] >> 16 == 0)
  2067. --resLength;
  2068. int[] res = new int[resLength];
  2069. Square(res, magnitude);
  2070. return new BigInteger(1, res, false);
  2071. }
  2072. public BigInteger Negate()
  2073. {
  2074. if (sign == 0)
  2075. return this;
  2076. return new BigInteger(-sign, magnitude, false);
  2077. }
  2078. public BigInteger NextProbablePrime()
  2079. {
  2080. if (sign < 0)
  2081. throw new ArithmeticException("Cannot be called on value < 0");
  2082. if (CompareTo(Two) < 0)
  2083. return Two;
  2084. BigInteger n = Inc().SetBit(0);
  2085. while (!n.CheckProbablePrime(100, RandomSource, false))
  2086. {
  2087. n = n.Add(Two);
  2088. }
  2089. return n;
  2090. }
  2091. public BigInteger Not()
  2092. {
  2093. return Inc().Negate();
  2094. }
  2095. public BigInteger Pow(int exp)
  2096. {
  2097. if (exp <= 0)
  2098. {
  2099. if (exp < 0)
  2100. throw new ArithmeticException("Negative exponent");
  2101. return One;
  2102. }
  2103. if (sign == 0)
  2104. {
  2105. return this;
  2106. }
  2107. if (QuickPow2Check())
  2108. {
  2109. long powOf2 = (long)exp * (BitLength - 1);
  2110. if (powOf2 > Int32.MaxValue)
  2111. {
  2112. throw new ArithmeticException("Result too large");
  2113. }
  2114. return One.ShiftLeft((int)powOf2);
  2115. }
  2116. BigInteger y = One;
  2117. BigInteger z = this;
  2118. for (;;)
  2119. {
  2120. if ((exp & 0x1) == 1)
  2121. {
  2122. y = y.Multiply(z);
  2123. }
  2124. exp >>= 1;
  2125. if (exp == 0) break;
  2126. z = z.Multiply(z);
  2127. }
  2128. return y;
  2129. }
  2130. public static BigInteger ProbablePrime(
  2131. int bitLength,
  2132. Random random)
  2133. {
  2134. return new BigInteger(bitLength, 100, random);
  2135. }
  2136. private int Remainder(
  2137. int m)
  2138. {
  2139. Debug.Assert(m > 0);
  2140. long acc = 0;
  2141. for (int pos = 0; pos < magnitude.Length; ++pos)
  2142. {
  2143. long posVal = (uint) magnitude[pos];
  2144. acc = (acc << 32 | posVal) % m;
  2145. }
  2146. return (int) acc;
  2147. }
  2148. /**
  2149. * return x = x % y - done in place (y value preserved)
  2150. */
  2151. private static int[] Remainder(
  2152. int[] x,
  2153. int[] y)
  2154. {
  2155. int xStart = 0;
  2156. while (xStart < x.Length && x[xStart] == 0)
  2157. {
  2158. ++xStart;
  2159. }
  2160. int yStart = 0;
  2161. while (yStart < y.Length && y[yStart] == 0)
  2162. {
  2163. ++yStart;
  2164. }
  2165. Debug.Assert(yStart < y.Length);
  2166. int xyCmp = CompareNoLeadingZeroes(xStart, x, yStart, y);
  2167. if (xyCmp > 0)
  2168. {
  2169. int yBitLength = CalcBitLength(1, yStart, y);
  2170. int xBitLength = CalcBitLength(1, xStart, x);
  2171. int shift = xBitLength - yBitLength;
  2172. int[] c;
  2173. int cStart = 0;
  2174. int cBitLength = yBitLength;
  2175. if (shift > 0)
  2176. {
  2177. c = ShiftLeft(y, shift);
  2178. cBitLength += shift;
  2179. Debug.Assert(c[0] != 0);
  2180. }
  2181. else
  2182. {
  2183. int len = y.Length - yStart;
  2184. c = new int[len];
  2185. Array.Copy(y, yStart, c, 0, len);
  2186. }
  2187. for (;;)
  2188. {
  2189. if (cBitLength < xBitLength
  2190. || CompareNoLeadingZeroes(xStart, x, cStart, c) >= 0)
  2191. {
  2192. Subtract(xStart, x, cStart, c);
  2193. while (x[xStart] == 0)
  2194. {
  2195. if (++xStart == x.Length)
  2196. return x;
  2197. }
  2198. //xBitLength = CalcBitLength(xStart, x);
  2199. xBitLength = 32 * (x.Length - xStart - 1) + BitLen(x[xStart]);
  2200. if (xBitLength <= yBitLength)
  2201. {
  2202. if (xBitLength < yBitLength)
  2203. return x;
  2204. xyCmp = CompareNoLeadingZeroes(xStart, x, yStart, y);
  2205. if (xyCmp <= 0)
  2206. break;
  2207. }
  2208. }
  2209. shift = cBitLength - xBitLength;
  2210. // NB: The case where c[cStart] is 1-bit is harmless
  2211. if (shift == 1)
  2212. {
  2213. uint firstC = (uint) c[cStart] >> 1;
  2214. uint firstX = (uint) x[xStart];
  2215. if (firstC > firstX)
  2216. ++shift;
  2217. }
  2218. if (shift < 2)
  2219. {
  2220. ShiftRightOneInPlace(cStart, c);
  2221. --cBitLength;
  2222. }
  2223. else
  2224. {
  2225. ShiftRightInPlace(cStart, c, shift);
  2226. cBitLength -= shift;
  2227. }
  2228. //cStart = c.Length - ((cBitLength + 31) / 32);
  2229. while (c[cStart] == 0)
  2230. {
  2231. ++cStart;
  2232. }
  2233. }
  2234. }
  2235. if (xyCmp == 0)
  2236. {
  2237. Array.Clear(x, xStart, x.Length - xStart);
  2238. }
  2239. return x;
  2240. }
  2241. public BigInteger Remainder(
  2242. BigInteger n)
  2243. {
  2244. if (n.sign == 0)
  2245. throw new ArithmeticException("Division by zero error");
  2246. if (this.sign == 0)
  2247. return Zero;
  2248. // For small values, use fast remainder method
  2249. if (n.magnitude.Length == 1)
  2250. {
  2251. int val = n.magnitude[0];
  2252. if (val > 0)
  2253. {
  2254. if (val == 1)
  2255. return Zero;
  2256. // TODO Make this func work on uint, and handle val == 1?
  2257. int rem = Remainder(val);
  2258. return rem == 0
  2259. ? Zero
  2260. : new BigInteger(sign, new int[]{ rem }, false);
  2261. }
  2262. }
  2263. if (CompareNoLeadingZeroes(0, magnitude, 0, n.magnitude) < 0)
  2264. return this;
  2265. int[] result;
  2266. if (n.QuickPow2Check()) // n is power of two
  2267. {
  2268. // TODO Move before small values branch above?
  2269. result = LastNBits(n.Abs().BitLength - 1);
  2270. }
  2271. else
  2272. {
  2273. result = (int[]) this.magnitude.Clone();
  2274. result = Remainder(result, n.magnitude);
  2275. }
  2276. return new BigInteger(sign, result, true);
  2277. }
  2278. private int[] LastNBits(
  2279. int n)
  2280. {
  2281. if (n < 1)
  2282. return ZeroMagnitude;
  2283. int numWords = (n + BitsPerInt - 1) / BitsPerInt;
  2284. numWords = System.Math.Min(numWords, this.magnitude.Length);
  2285. int[] result = new int[numWords];
  2286. Array.Copy(this.magnitude, this.magnitude.Length - numWords, result, 0, numWords);
  2287. int excessBits = (numWords << 5) - n;
  2288. if (excessBits > 0)
  2289. {
  2290. result[0] &= (int)(UInt32.MaxValue >> excessBits);
  2291. }
  2292. return result;
  2293. }
  2294. private BigInteger DivideWords(int w)
  2295. {
  2296. Debug.Assert(w >= 0);
  2297. int n = magnitude.Length;
  2298. if (w >= n)
  2299. return Zero;
  2300. int[] mag = new int[n - w];
  2301. Array.Copy(magnitude, 0, mag, 0, n - w);
  2302. return new BigInteger(sign, mag, false);
  2303. }
  2304. private BigInteger RemainderWords(int w)
  2305. {
  2306. Debug.Assert(w >= 0);
  2307. int n = magnitude.Length;
  2308. if (w >= n)
  2309. return this;
  2310. int[] mag = new int[w];
  2311. Array.Copy(magnitude, n - w, mag, 0, w);
  2312. return new BigInteger(sign, mag, false);
  2313. }
  2314. /**
  2315. * do a left shift - this returns a new array.
  2316. */
  2317. private static int[] ShiftLeft(
  2318. int[] mag,
  2319. int n)
  2320. {
  2321. int nInts = (int)((uint)n >> 5);
  2322. int nBits = n & 0x1f;
  2323. int magLen = mag.Length;
  2324. int[] newMag;
  2325. if (nBits == 0)
  2326. {
  2327. newMag = new int[magLen + nInts];
  2328. mag.CopyTo(newMag, 0);
  2329. }
  2330. else
  2331. {
  2332. int i = 0;
  2333. int nBits2 = 32 - nBits;
  2334. int highBits = (int)((uint)mag[0] >> nBits2);
  2335. if (highBits != 0)
  2336. {
  2337. newMag = new int[magLen + nInts + 1];
  2338. newMag[i++] = highBits;
  2339. }
  2340. else
  2341. {
  2342. newMag = new int[magLen + nInts];
  2343. }
  2344. int m = mag[0];
  2345. for (int j = 0; j < magLen - 1; j++)
  2346. {
  2347. int next = mag[j + 1];
  2348. newMag[i++] = (m << nBits) | (int)((uint)next >> nBits2);
  2349. m = next;
  2350. }
  2351. newMag[i] = mag[magLen - 1] << nBits;
  2352. }
  2353. return newMag;
  2354. }
  2355. private static int ShiftLeftOneInPlace(int[] x, int carry)
  2356. {
  2357. Debug.Assert(carry == 0 || carry == 1);
  2358. int pos = x.Length;
  2359. while (--pos >= 0)
  2360. {
  2361. uint val = (uint)x[pos];
  2362. x[pos] = (int)(val << 1) | carry;
  2363. carry = (int)(val >> 31);
  2364. }
  2365. return carry;
  2366. }
  2367. public BigInteger ShiftLeft(
  2368. int n)
  2369. {
  2370. if (sign == 0 || magnitude.Length == 0)
  2371. return Zero;
  2372. if (n == 0)
  2373. return this;
  2374. if (n < 0)
  2375. return ShiftRight(-n);
  2376. BigInteger result = new BigInteger(sign, ShiftLeft(magnitude, n), true);
  2377. if (this.nBits != -1)
  2378. {
  2379. result.nBits = sign > 0
  2380. ? this.nBits
  2381. : this.nBits + n;
  2382. }
  2383. if (this.nBitLength != -1)
  2384. {
  2385. result.nBitLength = this.nBitLength + n;
  2386. }
  2387. return result;
  2388. }
  2389. /**
  2390. * do a right shift - this does it in place.
  2391. */
  2392. private static void ShiftRightInPlace(
  2393. int start,
  2394. int[] mag,
  2395. int n)
  2396. {
  2397. int nInts = (int)((uint)n >> 5) + start;
  2398. int nBits = n & 0x1f;
  2399. int magEnd = mag.Length - 1;
  2400. if (nInts != start)
  2401. {
  2402. int delta = (nInts - start);
  2403. for (int i = magEnd; i >= nInts; i--)
  2404. {
  2405. mag[i] = mag[i - delta];
  2406. }
  2407. for (int i = nInts - 1; i >= start; i--)
  2408. {
  2409. mag[i] = 0;
  2410. }
  2411. }
  2412. if (nBits != 0)
  2413. {
  2414. int nBits2 = 32 - nBits;
  2415. int m = mag[magEnd];
  2416. for (int i = magEnd; i > nInts; --i)
  2417. {
  2418. int next = mag[i - 1];
  2419. mag[i] = (int)((uint)m >> nBits) | (next << nBits2);
  2420. m = next;
  2421. }
  2422. mag[nInts] = (int)((uint)mag[nInts] >> nBits);
  2423. }
  2424. }
  2425. /**
  2426. * do a right shift by one - this does it in place.
  2427. */
  2428. private static void ShiftRightOneInPlace(
  2429. int start,
  2430. int[] mag)
  2431. {
  2432. int i = mag.Length;
  2433. int m = mag[i - 1];
  2434. while (--i > start)
  2435. {
  2436. int next = mag[i - 1];
  2437. mag[i] = ((int)((uint)m >> 1)) | (next << 31);
  2438. m = next;
  2439. }
  2440. mag[start] = (int)((uint)mag[start] >> 1);
  2441. }
  2442. public BigInteger ShiftRight(
  2443. int n)
  2444. {
  2445. if (n == 0)
  2446. return this;
  2447. if (n < 0)
  2448. return ShiftLeft(-n);
  2449. if (n >= BitLength)
  2450. return (this.sign < 0 ? One.Negate() : Zero);
  2451. // int[] res = (int[]) this.magnitude.Clone();
  2452. //
  2453. // ShiftRightInPlace(0, res, n);
  2454. //
  2455. // return new BigInteger(this.sign, res, true);
  2456. int resultLength = (BitLength - n + 31) >> 5;
  2457. int[] res = new int[resultLength];
  2458. int numInts = n >> 5;
  2459. int numBits = n & 31;
  2460. if (numBits == 0)
  2461. {
  2462. Array.Copy(this.magnitude, 0, res, 0, res.Length);
  2463. }
  2464. else
  2465. {
  2466. int numBits2 = 32 - numBits;
  2467. int magPos = this.magnitude.Length - 1 - numInts;
  2468. for (int i = resultLength - 1; i >= 0; --i)
  2469. {
  2470. res[i] = (int)((uint) this.magnitude[magPos--] >> numBits);
  2471. if (magPos >= 0)
  2472. {
  2473. res[i] |= this.magnitude[magPos] << numBits2;
  2474. }
  2475. }
  2476. }
  2477. Debug.Assert(res[0] != 0);
  2478. return new BigInteger(this.sign, res, false);
  2479. }
  2480. public int SignValue
  2481. {
  2482. get { return sign; }
  2483. }
  2484. /**
  2485. * returns x = x - y - we assume x is >= y
  2486. */
  2487. private static int[] Subtract(
  2488. int xStart,
  2489. int[] x,
  2490. int yStart,
  2491. int[] y)
  2492. {
  2493. Debug.Assert(yStart < y.Length);
  2494. Debug.Assert(x.Length - xStart >= y.Length - yStart);
  2495. int iT = x.Length;
  2496. int iV = y.Length;
  2497. long m;
  2498. int borrow = 0;
  2499. do
  2500. {
  2501. m = (x[--iT] & IMASK) - (y[--iV] & IMASK) + borrow;
  2502. x[iT] = (int) m;
  2503. // borrow = (m < 0) ? -1 : 0;
  2504. borrow = (int)(m >> 63);
  2505. }
  2506. while (iV > yStart);
  2507. if (borrow != 0)
  2508. {
  2509. while (--x[--iT] == -1)
  2510. {
  2511. }
  2512. }
  2513. return x;
  2514. }
  2515. public BigInteger Subtract(
  2516. BigInteger n)
  2517. {
  2518. if (n.sign == 0)
  2519. return this;
  2520. if (this.sign == 0)
  2521. return n.Negate();
  2522. if (this.sign != n.sign)
  2523. return Add(n.Negate());
  2524. int compare = CompareNoLeadingZeroes(0, magnitude, 0, n.magnitude);
  2525. if (compare == 0)
  2526. return Zero;
  2527. BigInteger bigun, lilun;
  2528. if (compare < 0)
  2529. {
  2530. bigun = n;
  2531. lilun = this;
  2532. }
  2533. else
  2534. {
  2535. bigun = this;
  2536. lilun = n;
  2537. }
  2538. return new BigInteger(this.sign * compare, doSubBigLil(bigun.magnitude, lilun.magnitude), true);
  2539. }
  2540. private static int[] doSubBigLil(
  2541. int[] bigMag,
  2542. int[] lilMag)
  2543. {
  2544. int[] res = (int[]) bigMag.Clone();
  2545. return Subtract(0, res, 0, lilMag);
  2546. }
  2547. public byte[] ToByteArray()
  2548. {
  2549. return ToByteArray(false);
  2550. }
  2551. public byte[] ToByteArrayUnsigned()
  2552. {
  2553. return ToByteArray(true);
  2554. }
  2555. private byte[] ToByteArray(
  2556. bool unsigned)
  2557. {
  2558. if (sign == 0)
  2559. return unsigned ? ZeroEncoding : new byte[1];
  2560. int nBits = (unsigned && sign > 0)
  2561. ? BitLength
  2562. : BitLength + 1;
  2563. int nBytes = GetByteLength(nBits);
  2564. byte[] bytes = new byte[nBytes];
  2565. int magIndex = magnitude.Length;
  2566. int bytesIndex = bytes.Length;
  2567. if (sign > 0)
  2568. {
  2569. while (magIndex > 1)
  2570. {
  2571. uint mag = (uint) magnitude[--magIndex];
  2572. bytes[--bytesIndex] = (byte) mag;
  2573. bytes[--bytesIndex] = (byte)(mag >> 8);
  2574. bytes[--bytesIndex] = (byte)(mag >> 16);
  2575. bytes[--bytesIndex] = (byte)(mag >> 24);
  2576. }
  2577. uint lastMag = (uint) magnitude[0];
  2578. while (lastMag > byte.MaxValue)
  2579. {
  2580. bytes[--bytesIndex] = (byte) lastMag;
  2581. lastMag >>= 8;
  2582. }
  2583. bytes[--bytesIndex] = (byte) lastMag;
  2584. }
  2585. else // sign < 0
  2586. {
  2587. bool carry = true;
  2588. while (magIndex > 1)
  2589. {
  2590. uint mag = ~((uint) magnitude[--magIndex]);
  2591. if (carry)
  2592. {
  2593. carry = (++mag == uint.MinValue);
  2594. }
  2595. bytes[--bytesIndex] = (byte) mag;
  2596. bytes[--bytesIndex] = (byte)(mag >> 8);
  2597. bytes[--bytesIndex] = (byte)(mag >> 16);
  2598. bytes[--bytesIndex] = (byte)(mag >> 24);
  2599. }
  2600. uint lastMag = (uint) magnitude[0];
  2601. if (carry)
  2602. {
  2603. // Never wraps because magnitude[0] != 0
  2604. --lastMag;
  2605. }
  2606. while (lastMag > byte.MaxValue)
  2607. {
  2608. bytes[--bytesIndex] = (byte) ~lastMag;
  2609. lastMag >>= 8;
  2610. }
  2611. bytes[--bytesIndex] = (byte) ~lastMag;
  2612. if (bytesIndex > 0)
  2613. {
  2614. bytes[--bytesIndex] = byte.MaxValue;
  2615. }
  2616. }
  2617. return bytes;
  2618. }
  2619. public override string ToString()
  2620. {
  2621. return ToString(10);
  2622. }
  2623. public string ToString(int radix)
  2624. {
  2625. // TODO Make this method work for other radices (ideally 2 <= radix <= 36 as in Java)
  2626. switch (radix)
  2627. {
  2628. case 2:
  2629. case 8:
  2630. case 10:
  2631. case 16:
  2632. break;
  2633. default:
  2634. throw new FormatException("Only bases 2, 8, 10, 16 are allowed");
  2635. }
  2636. // NB: Can only happen to internally managed instances
  2637. if (magnitude == null)
  2638. return "null";
  2639. if (sign == 0)
  2640. return "0";
  2641. // NOTE: This *should* be unnecessary, since the magnitude *should* never have leading zero digits
  2642. int firstNonZero = 0;
  2643. while (firstNonZero < magnitude.Length)
  2644. {
  2645. if (magnitude[firstNonZero] != 0)
  2646. {
  2647. break;
  2648. }
  2649. ++firstNonZero;
  2650. }
  2651. if (firstNonZero == magnitude.Length)
  2652. {
  2653. return "0";
  2654. }
  2655. StringBuilder sb = new StringBuilder();
  2656. if (sign == -1)
  2657. {
  2658. sb.Append('-');
  2659. }
  2660. switch (radix)
  2661. {
  2662. case 2:
  2663. {
  2664. int pos = firstNonZero;
  2665. sb.Append(Convert.ToString(magnitude[pos], 2));
  2666. while (++pos < magnitude.Length)
  2667. {
  2668. AppendZeroExtendedString(sb, Convert.ToString(magnitude[pos], 2), 32);
  2669. }
  2670. break;
  2671. }
  2672. case 8:
  2673. {
  2674. int mask = (1 << 30) - 1;
  2675. BigInteger u = this.Abs();
  2676. int bits = u.BitLength;
  2677. IList S = Org.BouncyCastle.Utilities.Platform.CreateArrayList();
  2678. while (bits > 30)
  2679. {
  2680. S.Add(Convert.ToString(u.IntValue & mask, 8));
  2681. u = u.ShiftRight(30);
  2682. bits -= 30;
  2683. }
  2684. sb.Append(Convert.ToString(u.IntValue, 8));
  2685. for (int i = S.Count - 1; i >= 0; --i)
  2686. {
  2687. AppendZeroExtendedString(sb, (string)S[i], 10);
  2688. }
  2689. break;
  2690. }
  2691. case 16:
  2692. {
  2693. int pos = firstNonZero;
  2694. sb.Append(Convert.ToString(magnitude[pos], 16));
  2695. while (++pos < magnitude.Length)
  2696. {
  2697. AppendZeroExtendedString(sb, Convert.ToString(magnitude[pos], 16), 8);
  2698. }
  2699. break;
  2700. }
  2701. // TODO This could work for other radices if there is an alternative to Convert.ToString method
  2702. //default:
  2703. case 10:
  2704. {
  2705. BigInteger q = this.Abs();
  2706. if (q.BitLength < 64)
  2707. {
  2708. sb.Append(Convert.ToString(q.LongValue, radix));
  2709. break;
  2710. }
  2711. // Based on algorithm 1a from chapter 4.4 in Seminumerical Algorithms (Knuth)
  2712. // Work out the largest power of 'rdx' that is a positive 64-bit integer
  2713. // TODO possibly cache power/exponent against radix?
  2714. long limit = Int64.MaxValue / radix;
  2715. long power = radix;
  2716. int exponent = 1;
  2717. while (power <= limit)
  2718. {
  2719. power *= radix;
  2720. ++exponent;
  2721. }
  2722. BigInteger bigPower = BigInteger.ValueOf(power);
  2723. IList S = Org.BouncyCastle.Utilities.Platform.CreateArrayList();
  2724. while (q.CompareTo(bigPower) >= 0)
  2725. {
  2726. BigInteger[] qr = q.DivideAndRemainder(bigPower);
  2727. S.Add(Convert.ToString(qr[1].LongValue, radix));
  2728. q = qr[0];
  2729. }
  2730. sb.Append(Convert.ToString(q.LongValue, radix));
  2731. for (int i = S.Count - 1; i >= 0; --i)
  2732. {
  2733. AppendZeroExtendedString(sb, (string)S[i], exponent);
  2734. }
  2735. break;
  2736. }
  2737. }
  2738. return sb.ToString();
  2739. }
  2740. private static void AppendZeroExtendedString(StringBuilder sb, string s, int minLength)
  2741. {
  2742. for (int len = s.Length; len < minLength; ++len)
  2743. {
  2744. sb.Append('0');
  2745. }
  2746. sb.Append(s);
  2747. }
  2748. private static BigInteger CreateUValueOf(
  2749. ulong value)
  2750. {
  2751. int msw = (int)(value >> 32);
  2752. int lsw = (int)value;
  2753. if (msw != 0)
  2754. return new BigInteger(1, new int[] { msw, lsw }, false);
  2755. if (lsw != 0)
  2756. {
  2757. BigInteger n = new BigInteger(1, new int[] { lsw }, false);
  2758. // Check for a power of two
  2759. if ((lsw & -lsw) == lsw)
  2760. {
  2761. n.nBits = 1;
  2762. }
  2763. return n;
  2764. }
  2765. return Zero;
  2766. }
  2767. private static BigInteger CreateValueOf(
  2768. long value)
  2769. {
  2770. if (value < 0)
  2771. {
  2772. if (value == long.MinValue)
  2773. return CreateValueOf(~value).Not();
  2774. return CreateValueOf(-value).Negate();
  2775. }
  2776. return CreateUValueOf((ulong)value);
  2777. }
  2778. public static BigInteger ValueOf(
  2779. long value)
  2780. {
  2781. if (value >= 0 && value < SMALL_CONSTANTS.Length)
  2782. {
  2783. return SMALL_CONSTANTS[value];
  2784. }
  2785. return CreateValueOf(value);
  2786. }
  2787. public int GetLowestSetBit()
  2788. {
  2789. if (this.sign == 0)
  2790. return -1;
  2791. return GetLowestSetBitMaskFirst(-1);
  2792. }
  2793. private int GetLowestSetBitMaskFirst(int firstWordMask)
  2794. {
  2795. int w = magnitude.Length, offset = 0;
  2796. uint word = (uint)(magnitude[--w] & firstWordMask);
  2797. Debug.Assert(magnitude[0] != 0);
  2798. while (word == 0)
  2799. {
  2800. word = (uint)magnitude[--w];
  2801. offset += 32;
  2802. }
  2803. while ((word & 0xFF) == 0)
  2804. {
  2805. word >>= 8;
  2806. offset += 8;
  2807. }
  2808. while ((word & 1) == 0)
  2809. {
  2810. word >>= 1;
  2811. ++offset;
  2812. }
  2813. return offset;
  2814. }
  2815. public bool TestBit(
  2816. int n)
  2817. {
  2818. if (n < 0)
  2819. throw new ArithmeticException("Bit position must not be negative");
  2820. if (sign < 0)
  2821. return !Not().TestBit(n);
  2822. int wordNum = n / 32;
  2823. if (wordNum >= magnitude.Length)
  2824. return false;
  2825. int word = magnitude[magnitude.Length - 1 - wordNum];
  2826. return ((word >> (n % 32)) & 1) > 0;
  2827. }
  2828. public BigInteger Or(
  2829. BigInteger value)
  2830. {
  2831. if (this.sign == 0)
  2832. return value;
  2833. if (value.sign == 0)
  2834. return this;
  2835. int[] aMag = this.sign > 0
  2836. ? this.magnitude
  2837. : Add(One).magnitude;
  2838. int[] bMag = value.sign > 0
  2839. ? value.magnitude
  2840. : value.Add(One).magnitude;
  2841. bool resultNeg = sign < 0 || value.sign < 0;
  2842. int resultLength = System.Math.Max(aMag.Length, bMag.Length);
  2843. int[] resultMag = new int[resultLength];
  2844. int aStart = resultMag.Length - aMag.Length;
  2845. int bStart = resultMag.Length - bMag.Length;
  2846. for (int i = 0; i < resultMag.Length; ++i)
  2847. {
  2848. int aWord = i >= aStart ? aMag[i - aStart] : 0;
  2849. int bWord = i >= bStart ? bMag[i - bStart] : 0;
  2850. if (this.sign < 0)
  2851. {
  2852. aWord = ~aWord;
  2853. }
  2854. if (value.sign < 0)
  2855. {
  2856. bWord = ~bWord;
  2857. }
  2858. resultMag[i] = aWord | bWord;
  2859. if (resultNeg)
  2860. {
  2861. resultMag[i] = ~resultMag[i];
  2862. }
  2863. }
  2864. BigInteger result = new BigInteger(1, resultMag, true);
  2865. // TODO Optimise this case
  2866. if (resultNeg)
  2867. {
  2868. result = result.Not();
  2869. }
  2870. return result;
  2871. }
  2872. public BigInteger Xor(
  2873. BigInteger value)
  2874. {
  2875. if (this.sign == 0)
  2876. return value;
  2877. if (value.sign == 0)
  2878. return this;
  2879. int[] aMag = this.sign > 0
  2880. ? this.magnitude
  2881. : Add(One).magnitude;
  2882. int[] bMag = value.sign > 0
  2883. ? value.magnitude
  2884. : value.Add(One).magnitude;
  2885. // TODO Can just replace with sign != value.sign?
  2886. bool resultNeg = (sign < 0 && value.sign >= 0) || (sign >= 0 && value.sign < 0);
  2887. int resultLength = System.Math.Max(aMag.Length, bMag.Length);
  2888. int[] resultMag = new int[resultLength];
  2889. int aStart = resultMag.Length - aMag.Length;
  2890. int bStart = resultMag.Length - bMag.Length;
  2891. for (int i = 0; i < resultMag.Length; ++i)
  2892. {
  2893. int aWord = i >= aStart ? aMag[i - aStart] : 0;
  2894. int bWord = i >= bStart ? bMag[i - bStart] : 0;
  2895. if (this.sign < 0)
  2896. {
  2897. aWord = ~aWord;
  2898. }
  2899. if (value.sign < 0)
  2900. {
  2901. bWord = ~bWord;
  2902. }
  2903. resultMag[i] = aWord ^ bWord;
  2904. if (resultNeg)
  2905. {
  2906. resultMag[i] = ~resultMag[i];
  2907. }
  2908. }
  2909. BigInteger result = new BigInteger(1, resultMag, true);
  2910. // TODO Optimise this case
  2911. if (resultNeg)
  2912. {
  2913. result = result.Not();
  2914. }
  2915. return result;
  2916. }
  2917. public BigInteger SetBit(
  2918. int n)
  2919. {
  2920. if (n < 0)
  2921. throw new ArithmeticException("Bit address less than zero");
  2922. if (TestBit(n))
  2923. return this;
  2924. // TODO Handle negative values and zero
  2925. if (sign > 0 && n < (BitLength - 1))
  2926. return FlipExistingBit(n);
  2927. return Or(One.ShiftLeft(n));
  2928. }
  2929. public BigInteger ClearBit(
  2930. int n)
  2931. {
  2932. if (n < 0)
  2933. throw new ArithmeticException("Bit address less than zero");
  2934. if (!TestBit(n))
  2935. return this;
  2936. // TODO Handle negative values
  2937. if (sign > 0 && n < (BitLength - 1))
  2938. return FlipExistingBit(n);
  2939. return AndNot(One.ShiftLeft(n));
  2940. }
  2941. public BigInteger FlipBit(
  2942. int n)
  2943. {
  2944. if (n < 0)
  2945. throw new ArithmeticException("Bit address less than zero");
  2946. // TODO Handle negative values and zero
  2947. if (sign > 0 && n < (BitLength - 1))
  2948. return FlipExistingBit(n);
  2949. return Xor(One.ShiftLeft(n));
  2950. }
  2951. private BigInteger FlipExistingBit(
  2952. int n)
  2953. {
  2954. Debug.Assert(sign > 0);
  2955. Debug.Assert(n >= 0);
  2956. Debug.Assert(n < BitLength - 1);
  2957. int[] mag = (int[]) this.magnitude.Clone();
  2958. mag[mag.Length - 1 - (n >> 5)] ^= (1 << (n & 31)); // Flip bit
  2959. //mag[mag.Length - 1 - (n / 32)] ^= (1 << (n % 32));
  2960. return new BigInteger(this.sign, mag, false);
  2961. }
  2962. }
  2963. }
  2964. #endif