gmp.info-1 295 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053
  1. This is gmp.info, produced by makeinfo version 6.1 from gmp.texi.
  2. This manual describes how to install and use the GNU multiple precision
  3. arithmetic library, version 6.1.2.
  4. Copyright 1991, 1993-2016 Free Software Foundation, Inc.
  5. Permission is granted to copy, distribute and/or modify this document
  6. under the terms of the GNU Free Documentation License, Version 1.3 or
  7. any later version published by the Free Software Foundation; with no
  8. Invariant Sections, with the Front-Cover Texts being "A GNU Manual", and
  9. with the Back-Cover Texts being "You have freedom to copy and modify
  10. this GNU Manual, like GNU software". A copy of the license is included
  11. in *note GNU Free Documentation License::.
  12. INFO-DIR-SECTION GNU libraries
  13. START-INFO-DIR-ENTRY
  14. * gmp: (gmp). GNU Multiple Precision Arithmetic Library.
  15. END-INFO-DIR-ENTRY
  16. 
  17. File: gmp.info, Node: Top, Next: Copying, Prev: (dir), Up: (dir)
  18. GNU MP
  19. ******
  20. This manual describes how to install and use the GNU multiple precision
  21. arithmetic library, version 6.1.2.
  22. Copyright 1991, 1993-2016 Free Software Foundation, Inc.
  23. Permission is granted to copy, distribute and/or modify this document
  24. under the terms of the GNU Free Documentation License, Version 1.3 or
  25. any later version published by the Free Software Foundation; with no
  26. Invariant Sections, with the Front-Cover Texts being "A GNU Manual", and
  27. with the Back-Cover Texts being "You have freedom to copy and modify
  28. this GNU Manual, like GNU software". A copy of the license is included
  29. in *note GNU Free Documentation License::.
  30. * Menu:
  31. * Copying:: GMP Copying Conditions (LGPL).
  32. * Introduction to GMP:: Brief introduction to GNU MP.
  33. * Installing GMP:: How to configure and compile the GMP library.
  34. * GMP Basics:: What every GMP user should know.
  35. * Reporting Bugs:: How to usefully report bugs.
  36. * Integer Functions:: Functions for arithmetic on signed integers.
  37. * Rational Number Functions:: Functions for arithmetic on rational numbers.
  38. * Floating-point Functions:: Functions for arithmetic on floats.
  39. * Low-level Functions:: Fast functions for natural numbers.
  40. * Random Number Functions:: Functions for generating random numbers.
  41. * Formatted Output:: 'printf' style output.
  42. * Formatted Input:: 'scanf' style input.
  43. * C++ Class Interface:: Class wrappers around GMP types.
  44. * Custom Allocation:: How to customize the internal allocation.
  45. * Language Bindings:: Using GMP from other languages.
  46. * Algorithms:: What happens behind the scenes.
  47. * Internals:: How values are represented behind the scenes.
  48. * Contributors:: Who brings you this library?
  49. * References:: Some useful papers and books to read.
  50. * GNU Free Documentation License::
  51. * Concept Index::
  52. * Function Index::
  53. 
  54. File: gmp.info, Node: Copying, Next: Introduction to GMP, Prev: Top, Up: Top
  55. GNU MP Copying Conditions
  56. *************************
  57. This library is "free"; this means that everyone is free to use it and
  58. free to redistribute it on a free basis. The library is not in the
  59. public domain; it is copyrighted and there are restrictions on its
  60. distribution, but these restrictions are designed to permit everything
  61. that a good cooperating citizen would want to do. What is not allowed
  62. is to try to prevent others from further sharing any version of this
  63. library that they might get from you.
  64. Specifically, we want to make sure that you have the right to give
  65. away copies of the library, that you receive source code or else can get
  66. it if you want it, that you can change this library or use pieces of it
  67. in new free programs, and that you know you can do these things.
  68. To make sure that everyone has such rights, we have to forbid you to
  69. deprive anyone else of these rights. For example, if you distribute
  70. copies of the GNU MP library, you must give the recipients all the
  71. rights that you have. You must make sure that they, too, receive or can
  72. get the source code. And you must tell them their rights.
  73. Also, for our own protection, we must make certain that everyone
  74. finds out that there is no warranty for the GNU MP library. If it is
  75. modified by someone else and passed on, we want their recipients to know
  76. that what they have is not what we distributed, so that any problems
  77. introduced by others will not reflect on our reputation.
  78. More precisely, the GNU MP library is dual licensed, under the
  79. conditions of the GNU Lesser General Public License version 3 (see
  80. 'COPYING.LESSERv3'), or the GNU General Public License version 2 (see
  81. 'COPYINGv2'). This is the recipient's choice, and the recipient also
  82. has the additional option of applying later versions of these licenses.
  83. (The reason for this dual licensing is to make it possible to use the
  84. library with programs which are licensed under GPL version 2, but which
  85. for historical or other reasons do not allow use under later versions of
  86. the GPL).
  87. Programs which are not part of the library itself, such as
  88. demonstration programs and the GMP testsuite, are licensed under the
  89. terms of the GNU General Public License version 3 (see 'COPYINGv3'), or
  90. any later version.
  91. 
  92. File: gmp.info, Node: Introduction to GMP, Next: Installing GMP, Prev: Copying, Up: Top
  93. 1 Introduction to GNU MP
  94. ************************
  95. GNU MP is a portable library written in C for arbitrary precision
  96. arithmetic on integers, rational numbers, and floating-point numbers.
  97. It aims to provide the fastest possible arithmetic for all applications
  98. that need higher precision than is directly supported by the basic C
  99. types.
  100. Many applications use just a few hundred bits of precision; but some
  101. applications may need thousands or even millions of bits. GMP is
  102. designed to give good performance for both, by choosing algorithms based
  103. on the sizes of the operands, and by carefully keeping the overhead at a
  104. minimum.
  105. The speed of GMP is achieved by using fullwords as the basic
  106. arithmetic type, by using sophisticated algorithms, by including
  107. carefully optimized assembly code for the most common inner loops for
  108. many different CPUs, and by a general emphasis on speed (as opposed to
  109. simplicity or elegance).
  110. There is assembly code for these CPUs: ARM Cortex-A9, Cortex-A15, and
  111. generic ARM, DEC Alpha 21064, 21164, and 21264, AMD K8 and K10 (sold
  112. under many brands, e.g. Athlon64, Phenom, Opteron) Bulldozer, and
  113. Bobcat, Intel Pentium, Pentium Pro/II/III, Pentium 4, Core2, Nehalem,
  114. Sandy bridge, Haswell, generic x86, Intel IA-64, Motorola/IBM PowerPC 32
  115. and 64 such as POWER970, POWER5, POWER6, and POWER7, MIPS 32-bit and
  116. 64-bit, SPARC 32-bit ad 64-bit with special support for all UltraSPARC
  117. models. There is also assembly code for many obsolete CPUs.
  118. For up-to-date information on GMP, please see the GMP web pages at
  119. <https://gmplib.org/>
  120. The latest version of the library is available at
  121. <https://ftp.gnu.org/gnu/gmp/>
  122. Many sites around the world mirror 'ftp.gnu.org', please use a mirror
  123. near you, see <https://www.gnu.org/order/ftp.html> for a full list.
  124. There are three public mailing lists of interest. One for release
  125. announcements, one for general questions and discussions about usage of
  126. the GMP library and one for bug reports. For more information, see
  127. <https://gmplib.org/mailman/listinfo/>.
  128. The proper place for bug reports is <gmp-bugs@gmplib.org>. See *note
  129. Reporting Bugs:: for information about reporting bugs.
  130. 1.1 How to use this Manual
  131. ==========================
  132. Everyone should read *note GMP Basics::. If you need to install the
  133. library yourself, then read *note Installing GMP::. If you have a
  134. system with multiple ABIs, then read *note ABI and ISA::, for the
  135. compiler options that must be used on applications.
  136. The rest of the manual can be used for later reference, although it
  137. is probably a good idea to glance through it.
  138. 
  139. File: gmp.info, Node: Installing GMP, Next: GMP Basics, Prev: Introduction to GMP, Up: Top
  140. 2 Installing GMP
  141. ****************
  142. GMP has an autoconf/automake/libtool based configuration system. On a
  143. Unix-like system a basic build can be done with
  144. ./configure
  145. make
  146. Some self-tests can be run with
  147. make check
  148. And you can install (under '/usr/local' by default) with
  149. make install
  150. If you experience problems, please report them to
  151. <gmp-bugs@gmplib.org>. See *note Reporting Bugs::, for information on
  152. what to include in useful bug reports.
  153. * Menu:
  154. * Build Options::
  155. * ABI and ISA::
  156. * Notes for Package Builds::
  157. * Notes for Particular Systems::
  158. * Known Build Problems::
  159. * Performance optimization::
  160. 
  161. File: gmp.info, Node: Build Options, Next: ABI and ISA, Prev: Installing GMP, Up: Installing GMP
  162. 2.1 Build Options
  163. =================
  164. All the usual autoconf configure options are available, run './configure
  165. --help' for a summary. The file 'INSTALL.autoconf' has some generic
  166. installation information too.
  167. Tools
  168. 'configure' requires various Unix-like tools. See *note Notes for
  169. Particular Systems::, for some options on non-Unix systems.
  170. It might be possible to build without the help of 'configure',
  171. certainly all the code is there, but unfortunately you'll be on
  172. your own.
  173. Build Directory
  174. To compile in a separate build directory, 'cd' to that directory,
  175. and prefix the configure command with the path to the GMP source
  176. directory. For example
  177. cd /my/build/dir
  178. /my/sources/gmp-6.1.2/configure
  179. Not all 'make' programs have the necessary features ('VPATH') to
  180. support this. In particular, SunOS and Slowaris 'make' have bugs
  181. that make them unable to build in a separate directory. Use GNU
  182. 'make' instead.
  183. '--prefix' and '--exec-prefix'
  184. The '--prefix' option can be used in the normal way to direct GMP
  185. to install under a particular tree. The default is '/usr/local'.
  186. '--exec-prefix' can be used to direct architecture-dependent files
  187. like 'libgmp.a' to a different location. This can be used to share
  188. architecture-independent parts like the documentation, but separate
  189. the dependent parts. Note however that 'gmp.h' is
  190. architecture-dependent since it encodes certain aspects of
  191. 'libgmp', so it will be necessary to ensure both '$prefix/include'
  192. and '$exec_prefix/include' are available to the compiler.
  193. '--disable-shared', '--disable-static'
  194. By default both shared and static libraries are built (where
  195. possible), but one or other can be disabled. Shared libraries
  196. result in smaller executables and permit code sharing between
  197. separate running processes, but on some CPUs are slightly slower,
  198. having a small cost on each function call.
  199. Native Compilation, '--build=CPU-VENDOR-OS'
  200. For normal native compilation, the system can be specified with
  201. '--build'. By default './configure' uses the output from running
  202. './config.guess'. On some systems './config.guess' can determine
  203. the exact CPU type, on others it will be necessary to give it
  204. explicitly. For example,
  205. ./configure --build=ultrasparc-sun-solaris2.7
  206. In all cases the 'OS' part is important, since it controls how
  207. libtool generates shared libraries. Running './config.guess' is
  208. the simplest way to see what it should be, if you don't know
  209. already.
  210. Cross Compilation, '--host=CPU-VENDOR-OS'
  211. When cross-compiling, the system used for compiling is given by
  212. '--build' and the system where the library will run is given by
  213. '--host'. For example when using a FreeBSD Athlon system to build
  214. GNU/Linux m68k binaries,
  215. ./configure --build=athlon-pc-freebsd3.5 --host=m68k-mac-linux-gnu
  216. Compiler tools are sought first with the host system type as a
  217. prefix. For example 'm68k-mac-linux-gnu-ranlib' is tried, then
  218. plain 'ranlib'. This makes it possible for a set of
  219. cross-compiling tools to co-exist with native tools. The prefix is
  220. the argument to '--host', and this can be an alias, such as
  221. 'm68k-linux'. But note that tools don't have to be setup this way,
  222. it's enough to just have a 'PATH' with a suitable cross-compiling
  223. 'cc' etc.
  224. Compiling for a different CPU in the same family as the build
  225. system is a form of cross-compilation, though very possibly this
  226. would merely be special options on a native compiler. In any case
  227. './configure' avoids depending on being able to run code on the
  228. build system, which is important when creating binaries for a newer
  229. CPU since they very possibly won't run on the build system.
  230. In all cases the compiler must be able to produce an executable (of
  231. whatever format) from a standard C 'main'. Although only object
  232. files will go to make up 'libgmp', './configure' uses linking tests
  233. for various purposes, such as determining what functions are
  234. available on the host system.
  235. Currently a warning is given unless an explicit '--build' is used
  236. when cross-compiling, because it may not be possible to correctly
  237. guess the build system type if the 'PATH' has only a
  238. cross-compiling 'cc'.
  239. Note that the '--target' option is not appropriate for GMP. It's
  240. for use when building compiler tools, with '--host' being where
  241. they will run, and '--target' what they'll produce code for.
  242. Ordinary programs or libraries like GMP are only interested in the
  243. '--host' part, being where they'll run. (Some past versions of GMP
  244. used '--target' incorrectly.)
  245. CPU types
  246. In general, if you want a library that runs as fast as possible,
  247. you should configure GMP for the exact CPU type your system uses.
  248. However, this may mean the binaries won't run on older members of
  249. the family, and might run slower on other members, older or newer.
  250. The best idea is always to build GMP for the exact machine type you
  251. intend to run it on.
  252. The following CPUs have specific support. See 'configure.ac' for
  253. details of what code and compiler options they select.
  254. * Alpha: alpha, alphaev5, alphaev56, alphapca56, alphapca57,
  255. alphaev6, alphaev67, alphaev68 alphaev7
  256. * Cray: c90, j90, t90, sv1
  257. * HPPA: hppa1.0, hppa1.1, hppa2.0, hppa2.0n, hppa2.0w, hppa64
  258. * IA-64: ia64, itanium, itanium2
  259. * MIPS: mips, mips3, mips64
  260. * Motorola: m68k, m68000, m68010, m68020, m68030, m68040,
  261. m68060, m68302, m68360, m88k, m88110
  262. * POWER: power, power1, power2, power2sc
  263. * PowerPC: powerpc, powerpc64, powerpc401, powerpc403,
  264. powerpc405, powerpc505, powerpc601, powerpc602, powerpc603,
  265. powerpc603e, powerpc604, powerpc604e, powerpc620, powerpc630,
  266. powerpc740, powerpc7400, powerpc7450, powerpc750, powerpc801,
  267. powerpc821, powerpc823, powerpc860, powerpc970
  268. * SPARC: sparc, sparcv8, microsparc, supersparc, sparcv9,
  269. ultrasparc, ultrasparc2, ultrasparc2i, ultrasparc3, sparc64
  270. * x86 family: i386, i486, i586, pentium, pentiummmx, pentiumpro,
  271. pentium2, pentium3, pentium4, k6, k62, k63, athlon, amd64,
  272. viac3, viac32
  273. * Other: arm, sh, sh2, vax,
  274. CPUs not listed will use generic C code.
  275. Generic C Build
  276. If some of the assembly code causes problems, or if otherwise
  277. desired, the generic C code can be selected with the configure
  278. '--disable-assembly'.
  279. Note that this will run quite slowly, but it should be portable and
  280. should at least make it possible to get something running if all
  281. else fails.
  282. Fat binary, '--enable-fat'
  283. Using '--enable-fat' selects a "fat binary" build on x86, where
  284. optimized low level subroutines are chosen at runtime according to
  285. the CPU detected. This means more code, but gives good performance
  286. on all x86 chips. (This option might become available for more
  287. architectures in the future.)
  288. 'ABI'
  289. On some systems GMP supports multiple ABIs (application binary
  290. interfaces), meaning data type sizes and calling conventions. By
  291. default GMP chooses the best ABI available, but a particular ABI
  292. can be selected. For example
  293. ./configure --host=mips64-sgi-irix6 ABI=n32
  294. See *note ABI and ISA::, for the available choices on relevant
  295. CPUs, and what applications need to do.
  296. 'CC', 'CFLAGS'
  297. By default the C compiler used is chosen from among some likely
  298. candidates, with 'gcc' normally preferred if it's present. The
  299. usual 'CC=whatever' can be passed to './configure' to choose
  300. something different.
  301. For various systems, default compiler flags are set based on the
  302. CPU and compiler. The usual 'CFLAGS="-whatever"' can be passed to
  303. './configure' to use something different or to set good flags for
  304. systems GMP doesn't otherwise know.
  305. The 'CC' and 'CFLAGS' used are printed during './configure', and
  306. can be found in each generated 'Makefile'. This is the easiest way
  307. to check the defaults when considering changing or adding
  308. something.
  309. Note that when 'CC' and 'CFLAGS' are specified on a system
  310. supporting multiple ABIs it's important to give an explicit
  311. 'ABI=whatever', since GMP can't determine the ABI just from the
  312. flags and won't be able to select the correct assembly code.
  313. If just 'CC' is selected then normal default 'CFLAGS' for that
  314. compiler will be used (if GMP recognises it). For example 'CC=gcc'
  315. can be used to force the use of GCC, with default flags (and
  316. default ABI).
  317. 'CPPFLAGS'
  318. Any flags like '-D' defines or '-I' includes required by the
  319. preprocessor should be set in 'CPPFLAGS' rather than 'CFLAGS'.
  320. Compiling is done with both 'CPPFLAGS' and 'CFLAGS', but
  321. preprocessing uses just 'CPPFLAGS'. This distinction is because
  322. most preprocessors won't accept all the flags the compiler does.
  323. Preprocessing is done separately in some configure tests.
  324. 'CC_FOR_BUILD'
  325. Some build-time programs are compiled and run to generate
  326. host-specific data tables. 'CC_FOR_BUILD' is the compiler used for
  327. this. It doesn't need to be in any particular ABI or mode, it
  328. merely needs to generate executables that can run. The default is
  329. to try the selected 'CC' and some likely candidates such as 'cc'
  330. and 'gcc', looking for something that works.
  331. No flags are used with 'CC_FOR_BUILD' because a simple invocation
  332. like 'cc foo.c' should be enough. If some particular options are
  333. required they can be included as for instance 'CC_FOR_BUILD="cc
  334. -whatever"'.
  335. C++ Support, '--enable-cxx'
  336. C++ support in GMP can be enabled with '--enable-cxx', in which
  337. case a C++ compiler will be required. As a convenience
  338. '--enable-cxx=detect' can be used to enable C++ support only if a
  339. compiler can be found. The C++ support consists of a library
  340. 'libgmpxx.la' and header file 'gmpxx.h' (*note Headers and
  341. Libraries::).
  342. A separate 'libgmpxx.la' has been adopted rather than having C++
  343. objects within 'libgmp.la' in order to ensure dynamic linked C
  344. programs aren't bloated by a dependency on the C++ standard
  345. library, and to avoid any chance that the C++ compiler could be
  346. required when linking plain C programs.
  347. 'libgmpxx.la' will use certain internals from 'libgmp.la' and can
  348. only be expected to work with 'libgmp.la' from the same GMP
  349. version. Future changes to the relevant internals will be
  350. accompanied by renaming, so a mismatch will cause unresolved
  351. symbols rather than perhaps mysterious misbehaviour.
  352. In general 'libgmpxx.la' will be usable only with the C++ compiler
  353. that built it, since name mangling and runtime support are usually
  354. incompatible between different compilers.
  355. 'CXX', 'CXXFLAGS'
  356. When C++ support is enabled, the C++ compiler and its flags can be
  357. set with variables 'CXX' and 'CXXFLAGS' in the usual way. The
  358. default for 'CXX' is the first compiler that works from a list of
  359. likely candidates, with 'g++' normally preferred when available.
  360. The default for 'CXXFLAGS' is to try 'CFLAGS', 'CFLAGS' without
  361. '-g', then for 'g++' either '-g -O2' or '-O2', or for other
  362. compilers '-g' or nothing. Trying 'CFLAGS' this way is convenient
  363. when using 'gcc' and 'g++' together, since the flags for 'gcc' will
  364. usually suit 'g++'.
  365. It's important that the C and C++ compilers match, meaning their
  366. startup and runtime support routines are compatible and that they
  367. generate code in the same ABI (if there's a choice of ABIs on the
  368. system). './configure' isn't currently able to check these things
  369. very well itself, so for that reason '--disable-cxx' is the
  370. default, to avoid a build failure due to a compiler mismatch.
  371. Perhaps this will change in the future.
  372. Incidentally, it's normally not good enough to set 'CXX' to the
  373. same as 'CC'. Although 'gcc' for instance recognises 'foo.cc' as
  374. C++ code, only 'g++' will invoke the linker the right way when
  375. building an executable or shared library from C++ object files.
  376. Temporary Memory, '--enable-alloca=<choice>'
  377. GMP allocates temporary workspace using one of the following three
  378. methods, which can be selected with for instance
  379. '--enable-alloca=malloc-reentrant'.
  380. * 'alloca' - C library or compiler builtin.
  381. * 'malloc-reentrant' - the heap, in a re-entrant fashion.
  382. * 'malloc-notreentrant' - the heap, with global variables.
  383. For convenience, the following choices are also available.
  384. '--disable-alloca' is the same as 'no'.
  385. * 'yes' - a synonym for 'alloca'.
  386. * 'no' - a synonym for 'malloc-reentrant'.
  387. * 'reentrant' - 'alloca' if available, otherwise
  388. 'malloc-reentrant'. This is the default.
  389. * 'notreentrant' - 'alloca' if available, otherwise
  390. 'malloc-notreentrant'.
  391. 'alloca' is reentrant and fast, and is recommended. It actually
  392. allocates just small blocks on the stack; larger ones use
  393. malloc-reentrant.
  394. 'malloc-reentrant' is, as the name suggests, reentrant and thread
  395. safe, but 'malloc-notreentrant' is faster and should be used if
  396. reentrancy is not required.
  397. The two malloc methods in fact use the memory allocation functions
  398. selected by 'mp_set_memory_functions', these being 'malloc' and
  399. friends by default. *Note Custom Allocation::.
  400. An additional choice '--enable-alloca=debug' is available, to help
  401. when debugging memory related problems (*note Debugging::).
  402. FFT Multiplication, '--disable-fft'
  403. By default multiplications are done using Karatsuba, 3-way Toom,
  404. higher degree Toom, and Fermat FFT. The FFT is only used on large
  405. to very large operands and can be disabled to save code size if
  406. desired.
  407. Assertion Checking, '--enable-assert'
  408. This option enables some consistency checking within the library.
  409. This can be of use while debugging, *note Debugging::.
  410. Execution Profiling, '--enable-profiling=prof/gprof/instrument'
  411. Enable profiling support, in one of various styles, *note
  412. Profiling::.
  413. 'MPN_PATH'
  414. Various assembly versions of each mpn subroutines are provided.
  415. For a given CPU, a search is made though a path to choose a version
  416. of each. For example 'sparcv8' has
  417. MPN_PATH="sparc32/v8 sparc32 generic"
  418. which means look first for v8 code, then plain sparc32 (which is
  419. v7), and finally fall back on generic C. Knowledgeable users with
  420. special requirements can specify a different path. Normally this
  421. is completely unnecessary.
  422. Documentation
  423. The source for the document you're now reading is 'doc/gmp.texi',
  424. in Texinfo format, see *note Texinfo: (texinfo)Top.
  425. Info format 'doc/gmp.info' is included in the distribution. The
  426. usual automake targets are available to make PostScript, DVI, PDF
  427. and HTML (these will require various TeX and Texinfo tools).
  428. DocBook and XML can be generated by the Texinfo 'makeinfo' program
  429. too, see *note Options for 'makeinfo': (texinfo)makeinfo options.
  430. Some supplementary notes can also be found in the 'doc'
  431. subdirectory.
  432. 
  433. File: gmp.info, Node: ABI and ISA, Next: Notes for Package Builds, Prev: Build Options, Up: Installing GMP
  434. 2.2 ABI and ISA
  435. ===============
  436. ABI (Application Binary Interface) refers to the calling conventions
  437. between functions, meaning what registers are used and what sizes the
  438. various C data types are. ISA (Instruction Set Architecture) refers to
  439. the instructions and registers a CPU has available.
  440. Some 64-bit ISA CPUs have both a 64-bit ABI and a 32-bit ABI defined,
  441. the latter for compatibility with older CPUs in the family. GMP
  442. supports some CPUs like this in both ABIs. In fact within GMP 'ABI'
  443. means a combination of chip ABI, plus how GMP chooses to use it. For
  444. example in some 32-bit ABIs, GMP may support a limb as either a 32-bit
  445. 'long' or a 64-bit 'long long'.
  446. By default GMP chooses the best ABI available for a given system, and
  447. this generally gives significantly greater speed. But an ABI can be
  448. chosen explicitly to make GMP compatible with other libraries, or
  449. particular application requirements. For example,
  450. ./configure ABI=32
  451. In all cases it's vital that all object code used in a given program
  452. is compiled for the same ABI.
  453. Usually a limb is implemented as a 'long'. When a 'long long' limb
  454. is used this is encoded in the generated 'gmp.h'. This is convenient
  455. for applications, but it does mean that 'gmp.h' will vary, and can't be
  456. just copied around. 'gmp.h' remains compiler independent though, since
  457. all compilers for a particular ABI will be expected to use the same limb
  458. type.
  459. Currently no attempt is made to follow whatever conventions a system
  460. has for installing library or header files built for a particular ABI.
  461. This will probably only matter when installing multiple builds of GMP,
  462. and it might be as simple as configuring with a special 'libdir', or it
  463. might require more than that. Note that builds for different ABIs need
  464. to done separately, with a fresh './configure' and 'make' each.
  465. AMD64 ('x86_64')
  466. On AMD64 systems supporting both 32-bit and 64-bit modes for
  467. applications, the following ABI choices are available.
  468. 'ABI=64'
  469. The 64-bit ABI uses 64-bit limbs and pointers and makes full
  470. use of the chip architecture. This is the default.
  471. Applications will usually not need special compiler flags, but
  472. for reference the option is
  473. gcc -m64
  474. 'ABI=32'
  475. The 32-bit ABI is the usual i386 conventions. This will be
  476. slower, and is not recommended except for inter-operating with
  477. other code not yet 64-bit capable. Applications must be
  478. compiled with
  479. gcc -m32
  480. (In GCC 2.95 and earlier there's no '-m32' option, it's the
  481. only mode.)
  482. 'ABI=x32'
  483. The x32 ABI uses 64-bit limbs but 32-bit pointers. Like the
  484. 64-bit ABI, it makes full use of the chip's arithmetic
  485. capabilities. This ABI is not supported by all operating
  486. systems.
  487. gcc -mx32
  488. HPPA 2.0 ('hppa2.0*', 'hppa64')
  489. 'ABI=2.0w'
  490. The 2.0w ABI uses 64-bit limbs and pointers and is available
  491. on HP-UX 11 or up. Applications must be compiled with
  492. gcc [built for 2.0w]
  493. cc +DD64
  494. 'ABI=2.0n'
  495. The 2.0n ABI means the 32-bit HPPA 1.0 ABI and all its normal
  496. calling conventions, but with 64-bit instructions permitted
  497. within functions. GMP uses a 64-bit 'long long' for a limb.
  498. This ABI is available on hppa64 GNU/Linux and on HP-UX 10 or
  499. higher. Applications must be compiled with
  500. gcc [built for 2.0n]
  501. cc +DA2.0 +e
  502. Note that current versions of GCC (eg. 3.2) don't generate
  503. 64-bit instructions for 'long long' operations and so may be
  504. slower than for 2.0w. (The GMP assembly code is the same
  505. though.)
  506. 'ABI=1.0'
  507. HPPA 2.0 CPUs can run all HPPA 1.0 and 1.1 code in the 32-bit
  508. HPPA 1.0 ABI. No special compiler options are needed for
  509. applications.
  510. All three ABIs are available for CPU types 'hppa2.0w', 'hppa2.0'
  511. and 'hppa64', but for CPU type 'hppa2.0n' only 2.0n or 1.0 are
  512. considered.
  513. Note that GCC on HP-UX has no options to choose between 2.0n and
  514. 2.0w modes, unlike HP 'cc'. Instead it must be built for one or
  515. the other ABI. GMP will detect how it was built, and skip to the
  516. corresponding 'ABI'.
  517. IA-64 under HP-UX ('ia64*-*-hpux*', 'itanium*-*-hpux*')
  518. HP-UX supports two ABIs for IA-64. GMP performance is the same in
  519. both.
  520. 'ABI=32'
  521. In the 32-bit ABI, pointers, 'int's and 'long's are 32 bits
  522. and GMP uses a 64 bit 'long long' for a limb. Applications
  523. can be compiled without any special flags since this ABI is
  524. the default in both HP C and GCC, but for reference the flags
  525. are
  526. gcc -milp32
  527. cc +DD32
  528. 'ABI=64'
  529. In the 64-bit ABI, 'long's and pointers are 64 bits and GMP
  530. uses a 'long' for a limb. Applications must be compiled with
  531. gcc -mlp64
  532. cc +DD64
  533. On other IA-64 systems, GNU/Linux for instance, 'ABI=64' is the
  534. only choice.
  535. MIPS under IRIX 6 ('mips*-*-irix[6789]')
  536. IRIX 6 always has a 64-bit MIPS 3 or better CPU, and supports ABIs
  537. o32, n32, and 64. n32 or 64 are recommended, and GMP performance
  538. will be the same in each. The default is n32.
  539. 'ABI=o32'
  540. The o32 ABI is 32-bit pointers and integers, and no 64-bit
  541. operations. GMP will be slower than in n32 or 64, this option
  542. only exists to support old compilers, eg. GCC 2.7.2.
  543. Applications can be compiled with no special flags on an old
  544. compiler, or on a newer compiler with
  545. gcc -mabi=32
  546. cc -32
  547. 'ABI=n32'
  548. The n32 ABI is 32-bit pointers and integers, but with a 64-bit
  549. limb using a 'long long'. Applications must be compiled with
  550. gcc -mabi=n32
  551. cc -n32
  552. 'ABI=64'
  553. The 64-bit ABI is 64-bit pointers and integers. Applications
  554. must be compiled with
  555. gcc -mabi=64
  556. cc -64
  557. Note that MIPS GNU/Linux, as of kernel version 2.2, doesn't have
  558. the necessary support for n32 or 64 and so only gets a 32-bit limb
  559. and the MIPS 2 code.
  560. PowerPC 64 ('powerpc64', 'powerpc620', 'powerpc630', 'powerpc970', 'power4', 'power5')
  561. 'ABI=mode64'
  562. The AIX 64 ABI uses 64-bit limbs and pointers and is the
  563. default on PowerPC 64 '*-*-aix*' systems. Applications must
  564. be compiled with
  565. gcc -maix64
  566. xlc -q64
  567. On 64-bit GNU/Linux, BSD, and Mac OS X/Darwin systems, the
  568. applications must be compiled with
  569. gcc -m64
  570. 'ABI=mode32'
  571. The 'mode32' ABI uses a 64-bit 'long long' limb but with the
  572. chip still in 32-bit mode and using 32-bit calling
  573. conventions. This is the default for systems where the true
  574. 64-bit ABI is unavailable. No special compiler options are
  575. typically needed for applications. This ABI is not available
  576. under AIX.
  577. 'ABI=32'
  578. This is the basic 32-bit PowerPC ABI, with a 32-bit limb. No
  579. special compiler options are needed for applications.
  580. GMP's speed is greatest for the 'mode64' ABI, the 'mode32' ABI is
  581. 2nd best. In 'ABI=32' only the 32-bit ISA is used and this doesn't
  582. make full use of a 64-bit chip.
  583. Sparc V9 ('sparc64', 'sparcv9', 'ultrasparc*')
  584. 'ABI=64'
  585. The 64-bit V9 ABI is available on the various BSD sparc64
  586. ports, recent versions of Sparc64 GNU/Linux, and Solaris 2.7
  587. and up (when the kernel is in 64-bit mode). GCC 3.2 or
  588. higher, or Sun 'cc' is required. On GNU/Linux, depending on
  589. the default 'gcc' mode, applications must be compiled with
  590. gcc -m64
  591. On Solaris applications must be compiled with
  592. gcc -m64 -mptr64 -Wa,-xarch=v9 -mcpu=v9
  593. cc -xarch=v9
  594. On the BSD sparc64 systems no special options are required,
  595. since 64-bits is the only ABI available.
  596. 'ABI=32'
  597. For the basic 32-bit ABI, GMP still uses as much of the V9 ISA
  598. as it can. In the Sun documentation this combination is known
  599. as "v8plus". On GNU/Linux, depending on the default 'gcc'
  600. mode, applications may need to be compiled with
  601. gcc -m32
  602. On Solaris, no special compiler options are required for
  603. applications, though using something like the following is
  604. recommended. ('gcc' 2.8 and earlier only support '-mv8'
  605. though.)
  606. gcc -mv8plus
  607. cc -xarch=v8plus
  608. GMP speed is greatest in 'ABI=64', so it's the default where
  609. available. The speed is partly because there are extra registers
  610. available and partly because 64-bits is considered the more
  611. important case and has therefore had better code written for it.
  612. Don't be confused by the names of the '-m' and '-x' compiler
  613. options, they're called 'arch' but effectively control both ABI and
  614. ISA.
  615. On Solaris 2.6 and earlier, only 'ABI=32' is available since the
  616. kernel doesn't save all registers.
  617. On Solaris 2.7 with the kernel in 32-bit mode, a normal native
  618. build will reject 'ABI=64' because the resulting executables won't
  619. run. 'ABI=64' can still be built if desired by making it look like
  620. a cross-compile, for example
  621. ./configure --build=none --host=sparcv9-sun-solaris2.7 ABI=64
  622. 
  623. File: gmp.info, Node: Notes for Package Builds, Next: Notes for Particular Systems, Prev: ABI and ISA, Up: Installing GMP
  624. 2.3 Notes for Package Builds
  625. ============================
  626. GMP should present no great difficulties for packaging in a binary
  627. distribution.
  628. Libtool is used to build the library and '-version-info' is set
  629. appropriately, having started from '3:0:0' in GMP 3.0 (*note Library
  630. interface versions: (libtool)Versioning.).
  631. The GMP 4 series will be upwardly binary compatible in each release
  632. and will be upwardly binary compatible with all of the GMP 3 series.
  633. Additional function interfaces may be added in each release, so on
  634. systems where libtool versioning is not fully checked by the loader an
  635. auxiliary mechanism may be needed to express that a dynamic linked
  636. application depends on a new enough GMP.
  637. An auxiliary mechanism may also be needed to express that
  638. 'libgmpxx.la' (from '--enable-cxx', *note Build Options::) requires
  639. 'libgmp.la' from the same GMP version, since this is not done by the
  640. libtool versioning, nor otherwise. A mismatch will result in unresolved
  641. symbols from the linker, or perhaps the loader.
  642. When building a package for a CPU family, care should be taken to use
  643. '--host' (or '--build') to choose the least common denominator among the
  644. CPUs which might use the package. For example this might mean plain
  645. 'sparc' (meaning V7) for SPARCs.
  646. For x86s, '--enable-fat' sets things up for a fat binary build,
  647. making a runtime selection of optimized low level routines. This is a
  648. good choice for packaging to run on a range of x86 chips.
  649. Users who care about speed will want GMP built for their exact CPU
  650. type, to make best use of the available optimizations. Providing a way
  651. to suitably rebuild a package may be useful. This could be as simple as
  652. making it possible for a user to omit '--build' (and '--host') so
  653. './config.guess' will detect the CPU. But a way to manually specify a
  654. '--build' will be wanted for systems where './config.guess' is inexact.
  655. On systems with multiple ABIs, a packaged build will need to decide
  656. which among the choices is to be provided, see *note ABI and ISA::. A
  657. given run of './configure' etc will only build one ABI. If a second ABI
  658. is also required then a second run of './configure' etc must be made,
  659. starting from a clean directory tree ('make distclean').
  660. As noted under "ABI and ISA", currently no attempt is made to follow
  661. system conventions for install locations that vary with ABI, such as
  662. '/usr/lib/sparcv9' for 'ABI=64' as opposed to '/usr/lib' for 'ABI=32'.
  663. A package build can override 'libdir' and other standard variables as
  664. necessary.
  665. Note that 'gmp.h' is a generated file, and will be architecture and
  666. ABI dependent. When attempting to install two ABIs simultaneously it
  667. will be important that an application compile gets the correct 'gmp.h'
  668. for its desired ABI. If compiler include paths don't vary with ABI
  669. options then it might be necessary to create a '/usr/include/gmp.h'
  670. which tests preprocessor symbols and chooses the correct actual 'gmp.h'.
  671. 
  672. File: gmp.info, Node: Notes for Particular Systems, Next: Known Build Problems, Prev: Notes for Package Builds, Up: Installing GMP
  673. 2.4 Notes for Particular Systems
  674. ================================
  675. AIX 3 and 4
  676. On systems '*-*-aix[34]*' shared libraries are disabled by default,
  677. since some versions of the native 'ar' fail on the convenience
  678. libraries used. A shared build can be attempted with
  679. ./configure --enable-shared --disable-static
  680. Note that the '--disable-static' is necessary because in a shared
  681. build libtool makes 'libgmp.a' a symlink to 'libgmp.so', apparently
  682. for the benefit of old versions of 'ld' which only recognise '.a',
  683. but unfortunately this is done even if a fully functional 'ld' is
  684. available.
  685. ARM
  686. On systems 'arm*-*-*', versions of GCC up to and including 2.95.3
  687. have a bug in unsigned division, giving wrong results for some
  688. operands. GMP './configure' will demand GCC 2.95.4 or later.
  689. Compaq C++
  690. Compaq C++ on OSF 5.1 has two flavours of 'iostream', a standard
  691. one and an old pre-standard one (see 'man iostream_intro'). GMP
  692. can only use the standard one, which unfortunately is not the
  693. default but must be selected by defining '__USE_STD_IOSTREAM'.
  694. Configure with for instance
  695. ./configure --enable-cxx CPPFLAGS=-D__USE_STD_IOSTREAM
  696. Floating Point Mode
  697. On some systems, the hardware floating point has a control mode
  698. which can set all operations to be done in a particular precision,
  699. for instance single, double or extended on x86 systems (x87
  700. floating point). The GMP functions involving a 'double' cannot be
  701. expected to operate to their full precision when the hardware is in
  702. single precision mode. Of course this affects all code, including
  703. application code, not just GMP.
  704. FreeBSD 7.x, 8.x, 9.0, 9.1, 9.2
  705. 'm4' in these releases of FreeBSD has an eval function which
  706. ignores its 2nd and 3rd arguments, which makes it unsuitable for
  707. '.asm' file processing. './configure' will detect the problem and
  708. either abort or choose another m4 in the 'PATH'. The bug is fixed
  709. in FreeBSD 9.3 and 10.0, so either upgrade or use GNU m4. Note
  710. that the FreeBSD package system installs GNU m4 under the name
  711. 'gm4', which GMP cannot guess.
  712. FreeBSD 7.x, 8.x, 9.x
  713. GMP releases starting with 6.0 do not support 'ABI=32' on
  714. FreeBSD/amd64 prior to release 10.0 of the system. The cause is a
  715. broken 'limits.h', which GMP no longer works around.
  716. MS-DOS and MS Windows
  717. On an MS-DOS system DJGPP can be used to build GMP, and on an MS
  718. Windows system Cygwin, DJGPP and MINGW can be used. All three are
  719. excellent ports of GCC and the various GNU tools.
  720. <http://www.cygwin.com/>
  721. <http://www.delorie.com/djgpp/>
  722. <http://www.mingw.org/>
  723. Microsoft also publishes an Interix "Services for Unix" which can
  724. be used to build GMP on Windows (with a normal './configure'), but
  725. it's not free software.
  726. MS Windows DLLs
  727. On systems '*-*-cygwin*', '*-*-mingw*' and '*-*-pw32*' by default
  728. GMP builds only a static library, but a DLL can be built instead
  729. using
  730. ./configure --disable-static --enable-shared
  731. Static and DLL libraries can't both be built, since certain export
  732. directives in 'gmp.h' must be different.
  733. A MINGW DLL build of GMP can be used with Microsoft C. Libtool
  734. doesn't install a '.lib' format import library, but it can be
  735. created with MS 'lib' as follows, and copied to the install
  736. directory. Similarly for 'libmp' and 'libgmpxx'.
  737. cd .libs
  738. lib /def:libgmp-3.dll.def /out:libgmp-3.lib
  739. MINGW uses the C runtime library 'msvcrt.dll' for I/O, so
  740. applications wanting to use the GMP I/O routines must be compiled
  741. with 'cl /MD' to do the same. If one of the other C runtime
  742. library choices provided by MS C is desired then the suggestion is
  743. to use the GMP string functions and confine I/O to the application.
  744. Motorola 68k CPU Types
  745. 'm68k' is taken to mean 68000. 'm68020' or higher will give a
  746. performance boost on applicable CPUs. 'm68360' can be used for
  747. CPU32 series chips. 'm68302' can be used for "Dragonball" series
  748. chips, though this is merely a synonym for 'm68000'.
  749. NetBSD 5.x
  750. 'm4' in these releases of NetBSD has an eval function which ignores
  751. its 2nd and 3rd arguments, which makes it unsuitable for '.asm'
  752. file processing. './configure' will detect the problem and either
  753. abort or choose another m4 in the 'PATH'. The bug is fixed in
  754. NetBSD 6, so either upgrade or use GNU m4. Note that the NetBSD
  755. package system installs GNU m4 under the name 'gm4', which GMP
  756. cannot guess.
  757. OpenBSD 2.6
  758. 'm4' in this release of OpenBSD has a bug in 'eval' that makes it
  759. unsuitable for '.asm' file processing. './configure' will detect
  760. the problem and either abort or choose another m4 in the 'PATH'.
  761. The bug is fixed in OpenBSD 2.7, so either upgrade or use GNU m4.
  762. Power CPU Types
  763. In GMP, CPU types 'power*' and 'powerpc*' will each use
  764. instructions not available on the other, so it's important to
  765. choose the right one for the CPU that will be used. Currently GMP
  766. has no assembly code support for using just the common instruction
  767. subset. To get executables that run on both, the current
  768. suggestion is to use the generic C code ('--disable-assembly'),
  769. possibly with appropriate compiler options (like '-mcpu=common' for
  770. 'gcc'). CPU 'rs6000' (which is not a CPU but a family of
  771. workstations) is accepted by 'config.sub', but is currently
  772. equivalent to '--disable-assembly'.
  773. Sparc CPU Types
  774. 'sparcv8' or 'supersparc' on relevant systems will give a
  775. significant performance increase over the V7 code selected by plain
  776. 'sparc'.
  777. Sparc App Regs
  778. The GMP assembly code for both 32-bit and 64-bit Sparc clobbers the
  779. "application registers" 'g2', 'g3' and 'g4', the same way that the
  780. GCC default '-mapp-regs' does (*note SPARC Options: (gcc)SPARC
  781. Options.).
  782. This makes that code unsuitable for use with the special V9
  783. '-mcmodel=embmedany' (which uses 'g4' as a data segment pointer),
  784. and for applications wanting to use those registers for special
  785. purposes. In these cases the only suggestion currently is to build
  786. GMP with '--disable-assembly' to avoid the assembly code.
  787. SunOS 4
  788. '/usr/bin/m4' lacks various features needed to process '.asm'
  789. files, and instead './configure' will automatically use
  790. '/usr/5bin/m4', which we believe is always available (if not then
  791. use GNU m4).
  792. x86 CPU Types
  793. 'i586', 'pentium' or 'pentiummmx' code is good for its intended P5
  794. Pentium chips, but quite slow when run on Intel P6 class chips
  795. (PPro, P-II, P-III). 'i386' is a better choice when making
  796. binaries that must run on both.
  797. x86 MMX and SSE2 Code
  798. If the CPU selected has MMX code but the assembler doesn't support
  799. it, a warning is given and non-MMX code is used instead. This will
  800. be an inferior build, since the MMX code that's present is there
  801. because it's faster than the corresponding plain integer code. The
  802. same applies to SSE2.
  803. Old versions of 'gas' don't support MMX instructions, in particular
  804. version 1.92.3 that comes with FreeBSD 2.2.8 or the more recent
  805. OpenBSD 3.1 doesn't.
  806. Solaris 2.6 and 2.7 'as' generate incorrect object code for
  807. register to register 'movq' instructions, and so can't be used for
  808. MMX code. Install a recent 'gas' if MMX code is wanted on these
  809. systems.
  810. 
  811. File: gmp.info, Node: Known Build Problems, Next: Performance optimization, Prev: Notes for Particular Systems, Up: Installing GMP
  812. 2.5 Known Build Problems
  813. ========================
  814. You might find more up-to-date information at <https://gmplib.org/>.
  815. Compiler link options
  816. The version of libtool currently in use rather aggressively strips
  817. compiler options when linking a shared library. This will
  818. hopefully be relaxed in the future, but for now if this is a
  819. problem the suggestion is to create a little script to hide them,
  820. and for instance configure with
  821. ./configure CC=gcc-with-my-options
  822. DJGPP ('*-*-msdosdjgpp*')
  823. The DJGPP port of 'bash' 2.03 is unable to run the 'configure'
  824. script, it exits silently, having died writing a preamble to
  825. 'config.log'. Use 'bash' 2.04 or higher.
  826. 'make all' was found to run out of memory during the final
  827. 'libgmp.la' link on one system tested, despite having 64Mb
  828. available. Running 'make libgmp.la' directly helped, perhaps
  829. recursing into the various subdirectories uses up memory.
  830. GNU binutils 'strip' prior to 2.12
  831. 'strip' from GNU binutils 2.11 and earlier should not be used on
  832. the static libraries 'libgmp.a' and 'libmp.a' since it will discard
  833. all but the last of multiple archive members with the same name,
  834. like the three versions of 'init.o' in 'libgmp.a'. Binutils 2.12
  835. or higher can be used successfully.
  836. The shared libraries 'libgmp.so' and 'libmp.so' are not affected by
  837. this and any version of 'strip' can be used on them.
  838. 'make' syntax error
  839. On certain versions of SCO OpenServer 5 and IRIX 6.5 the native
  840. 'make' is unable to handle the long dependencies list for
  841. 'libgmp.la'. The symptom is a "syntax error" on the following line
  842. of the top-level 'Makefile'.
  843. libgmp.la: $(libgmp_la_OBJECTS) $(libgmp_la_DEPENDENCIES)
  844. Either use GNU Make, or as a workaround remove
  845. '$(libgmp_la_DEPENDENCIES)' from that line (which will make the
  846. initial build work, but if any recompiling is done 'libgmp.la'
  847. might not be rebuilt).
  848. MacOS X ('*-*-darwin*')
  849. Libtool currently only knows how to create shared libraries on
  850. MacOS X using the native 'cc' (which is a modified GCC), not a
  851. plain GCC. A static-only build should work though
  852. ('--disable-shared').
  853. NeXT prior to 3.3
  854. The system compiler on old versions of NeXT was a massacred and old
  855. GCC, even if it called itself 'cc'. This compiler cannot be used
  856. to build GMP, you need to get a real GCC, and install that. (NeXT
  857. may have fixed this in release 3.3 of their system.)
  858. POWER and PowerPC
  859. Bugs in GCC 2.7.2 (and 2.6.3) mean it can't be used to compile GMP
  860. on POWER or PowerPC. If you want to use GCC for these machines,
  861. get GCC 2.7.2.1 (or later).
  862. Sequent Symmetry
  863. Use the GNU assembler instead of the system assembler, since the
  864. latter has serious bugs.
  865. Solaris 2.6
  866. The system 'sed' prints an error "Output line too long" when
  867. libtool builds 'libgmp.la'. This doesn't seem to cause any obvious
  868. ill effects, but GNU 'sed' is recommended, to avoid any doubt.
  869. Sparc Solaris 2.7 with gcc 2.95.2 in 'ABI=32'
  870. A shared library build of GMP seems to fail in this combination, it
  871. builds but then fails the tests, apparently due to some incorrect
  872. data relocations within 'gmp_randinit_lc_2exp_size'. The exact
  873. cause is unknown, '--disable-shared' is recommended.
  874. 
  875. File: gmp.info, Node: Performance optimization, Prev: Known Build Problems, Up: Installing GMP
  876. 2.6 Performance optimization
  877. ============================
  878. For optimal performance, build GMP for the exact CPU type of the target
  879. computer, see *note Build Options::.
  880. Unlike what is the case for most other programs, the compiler
  881. typically doesn't matter much, since GMP uses assembly language for the
  882. most critical operation.
  883. In particular for long-running GMP applications, and applications
  884. demanding extremely large numbers, building and running the 'tuneup'
  885. program in the 'tune' subdirectory, can be important. For example,
  886. cd tune
  887. make tuneup
  888. ./tuneup
  889. will generate better contents for the 'gmp-mparam.h' parameter file.
  890. To use the results, put the output in the file indicated in the
  891. 'Parameters for ...' header. Then recompile from scratch.
  892. The 'tuneup' program takes one useful parameter, '-f NNN', which
  893. instructs the program how long to check FFT multiply parameters. If
  894. you're going to use GMP for extremely large numbers, you may want to run
  895. 'tuneup' with a large NNN value.
  896. 
  897. File: gmp.info, Node: GMP Basics, Next: Reporting Bugs, Prev: Installing GMP, Up: Top
  898. 3 GMP Basics
  899. ************
  900. *Using functions, macros, data types, etc. not documented in this manual
  901. is strongly discouraged. If you do so your application is guaranteed to
  902. be incompatible with future versions of GMP.*
  903. * Menu:
  904. * Headers and Libraries::
  905. * Nomenclature and Types::
  906. * Function Classes::
  907. * Variable Conventions::
  908. * Parameter Conventions::
  909. * Memory Management::
  910. * Reentrancy::
  911. * Useful Macros and Constants::
  912. * Compatibility with older versions::
  913. * Demonstration Programs::
  914. * Efficiency::
  915. * Debugging::
  916. * Profiling::
  917. * Autoconf::
  918. * Emacs::
  919. 
  920. File: gmp.info, Node: Headers and Libraries, Next: Nomenclature and Types, Prev: GMP Basics, Up: GMP Basics
  921. 3.1 Headers and Libraries
  922. =========================
  923. All declarations needed to use GMP are collected in the include file
  924. 'gmp.h'. It is designed to work with both C and C++ compilers.
  925. #include <gmp.h>
  926. Note however that prototypes for GMP functions with 'FILE *'
  927. parameters are only provided if '<stdio.h>' is included too.
  928. #include <stdio.h>
  929. #include <gmp.h>
  930. Likewise '<stdarg.h>' is required for prototypes with 'va_list'
  931. parameters, such as 'gmp_vprintf'. And '<obstack.h>' for prototypes
  932. with 'struct obstack' parameters, such as 'gmp_obstack_printf', when
  933. available.
  934. All programs using GMP must link against the 'libgmp' library. On a
  935. typical Unix-like system this can be done with '-lgmp', for example
  936. gcc myprogram.c -lgmp
  937. GMP C++ functions are in a separate 'libgmpxx' library. This is
  938. built and installed if C++ support has been enabled (*note Build
  939. Options::). For example,
  940. g++ mycxxprog.cc -lgmpxx -lgmp
  941. GMP is built using Libtool and an application can use that to link if
  942. desired, *note GNU Libtool: (libtool)Top.
  943. If GMP has been installed to a non-standard location then it may be
  944. necessary to use '-I' and '-L' compiler options to point to the right
  945. directories, and some sort of run-time path for a shared library.
  946. 
  947. File: gmp.info, Node: Nomenclature and Types, Next: Function Classes, Prev: Headers and Libraries, Up: GMP Basics
  948. 3.2 Nomenclature and Types
  949. ==========================
  950. In this manual, "integer" usually means a multiple precision integer, as
  951. defined by the GMP library. The C data type for such integers is
  952. 'mpz_t'. Here are some examples of how to declare such integers:
  953. mpz_t sum;
  954. struct foo { mpz_t x, y; };
  955. mpz_t vec[20];
  956. "Rational number" means a multiple precision fraction. The C data
  957. type for these fractions is 'mpq_t'. For example:
  958. mpq_t quotient;
  959. "Floating point number" or "Float" for short, is an arbitrary
  960. precision mantissa with a limited precision exponent. The C data type
  961. for such objects is 'mpf_t'. For example:
  962. mpf_t fp;
  963. The floating point functions accept and return exponents in the C
  964. type 'mp_exp_t'. Currently this is usually a 'long', but on some
  965. systems it's an 'int' for efficiency.
  966. A "limb" means the part of a multi-precision number that fits in a
  967. single machine word. (We chose this word because a limb of the human
  968. body is analogous to a digit, only larger, and containing several
  969. digits.) Normally a limb is 32 or 64 bits. The C data type for a limb
  970. is 'mp_limb_t'.
  971. Counts of limbs of a multi-precision number represented in the C type
  972. 'mp_size_t'. Currently this is normally a 'long', but on some systems
  973. it's an 'int' for efficiency, and on some systems it will be 'long long'
  974. in the future.
  975. Counts of bits of a multi-precision number are represented in the C
  976. type 'mp_bitcnt_t'. Currently this is always an 'unsigned long', but on
  977. some systems it will be an 'unsigned long long' in the future.
  978. "Random state" means an algorithm selection and current state data.
  979. The C data type for such objects is 'gmp_randstate_t'. For example:
  980. gmp_randstate_t rstate;
  981. Also, in general 'mp_bitcnt_t' is used for bit counts and ranges, and
  982. 'size_t' is used for byte or character counts.
  983. 
  984. File: gmp.info, Node: Function Classes, Next: Variable Conventions, Prev: Nomenclature and Types, Up: GMP Basics
  985. 3.3 Function Classes
  986. ====================
  987. There are six classes of functions in the GMP library:
  988. 1. Functions for signed integer arithmetic, with names beginning with
  989. 'mpz_'. The associated type is 'mpz_t'. There are about 150
  990. functions in this class. (*note Integer Functions::)
  991. 2. Functions for rational number arithmetic, with names beginning with
  992. 'mpq_'. The associated type is 'mpq_t'. There are about 35
  993. functions in this class, but the integer functions can be used for
  994. arithmetic on the numerator and denominator separately. (*note
  995. Rational Number Functions::)
  996. 3. Functions for floating-point arithmetic, with names beginning with
  997. 'mpf_'. The associated type is 'mpf_t'. There are about 70
  998. functions is this class. (*note Floating-point Functions::)
  999. 4. Fast low-level functions that operate on natural numbers. These
  1000. are used by the functions in the preceding groups, and you can also
  1001. call them directly from very time-critical user programs. These
  1002. functions' names begin with 'mpn_'. The associated type is array
  1003. of 'mp_limb_t'. There are about 60 (hard-to-use) functions in this
  1004. class. (*note Low-level Functions::)
  1005. 5. Miscellaneous functions. Functions for setting up custom
  1006. allocation and functions for generating random numbers. (*note
  1007. Custom Allocation::, and *note Random Number Functions::)
  1008. 
  1009. File: gmp.info, Node: Variable Conventions, Next: Parameter Conventions, Prev: Function Classes, Up: GMP Basics
  1010. 3.4 Variable Conventions
  1011. ========================
  1012. GMP functions generally have output arguments before input arguments.
  1013. This notation is by analogy with the assignment operator. The BSD MP
  1014. compatibility functions are exceptions, having the output arguments
  1015. last.
  1016. GMP lets you use the same variable for both input and output in one
  1017. call. For example, the main function for integer multiplication,
  1018. 'mpz_mul', can be used to square 'x' and put the result back in 'x' with
  1019. mpz_mul (x, x, x);
  1020. Before you can assign to a GMP variable, you need to initialize it by
  1021. calling one of the special initialization functions. When you're done
  1022. with a variable, you need to clear it out, using one of the functions
  1023. for that purpose. Which function to use depends on the type of
  1024. variable. See the chapters on integer functions, rational number
  1025. functions, and floating-point functions for details.
  1026. A variable should only be initialized once, or at least cleared
  1027. between each initialization. After a variable has been initialized, it
  1028. may be assigned to any number of times.
  1029. For efficiency reasons, avoid excessive initializing and clearing.
  1030. In general, initialize near the start of a function and clear near the
  1031. end. For example,
  1032. void
  1033. foo (void)
  1034. {
  1035. mpz_t n;
  1036. int i;
  1037. mpz_init (n);
  1038. for (i = 1; i < 100; i++)
  1039. {
  1040. mpz_mul (n, ...);
  1041. mpz_fdiv_q (n, ...);
  1042. ...
  1043. }
  1044. mpz_clear (n);
  1045. }
  1046. 
  1047. File: gmp.info, Node: Parameter Conventions, Next: Memory Management, Prev: Variable Conventions, Up: GMP Basics
  1048. 3.5 Parameter Conventions
  1049. =========================
  1050. When a GMP variable is used as a function parameter, it's effectively a
  1051. call-by-reference, meaning if the function stores a value there it will
  1052. change the original in the caller. Parameters which are input-only can
  1053. be designated 'const' to provoke a compiler error or warning on
  1054. attempting to modify them.
  1055. When a function is going to return a GMP result, it should designate
  1056. a parameter that it sets, like the library functions do. More than one
  1057. value can be returned by having more than one output parameter, again
  1058. like the library functions. A 'return' of an 'mpz_t' etc doesn't return
  1059. the object, only a pointer, and this is almost certainly not what's
  1060. wanted.
  1061. Here's an example accepting an 'mpz_t' parameter, doing a
  1062. calculation, and storing the result to the indicated parameter.
  1063. void
  1064. foo (mpz_t result, const mpz_t param, unsigned long n)
  1065. {
  1066. unsigned long i;
  1067. mpz_mul_ui (result, param, n);
  1068. for (i = 1; i < n; i++)
  1069. mpz_add_ui (result, result, i*7);
  1070. }
  1071. int
  1072. main (void)
  1073. {
  1074. mpz_t r, n;
  1075. mpz_init (r);
  1076. mpz_init_set_str (n, "123456", 0);
  1077. foo (r, n, 20L);
  1078. gmp_printf ("%Zd\n", r);
  1079. return 0;
  1080. }
  1081. 'foo' works even if the mainline passes the same variable for 'param'
  1082. and 'result', just like the library functions. But sometimes it's
  1083. tricky to make that work, and an application might not want to bother
  1084. supporting that sort of thing.
  1085. For interest, the GMP types 'mpz_t' etc are implemented as
  1086. one-element arrays of certain structures. This is why declaring a
  1087. variable creates an object with the fields GMP needs, but then using it
  1088. as a parameter passes a pointer to the object. Note that the actual
  1089. fields in each 'mpz_t' etc are for internal use only and should not be
  1090. accessed directly by code that expects to be compatible with future GMP
  1091. releases.
  1092. 
  1093. File: gmp.info, Node: Memory Management, Next: Reentrancy, Prev: Parameter Conventions, Up: GMP Basics
  1094. 3.6 Memory Management
  1095. =====================
  1096. The GMP types like 'mpz_t' are small, containing only a couple of sizes,
  1097. and pointers to allocated data. Once a variable is initialized, GMP
  1098. takes care of all space allocation. Additional space is allocated
  1099. whenever a variable doesn't have enough.
  1100. 'mpz_t' and 'mpq_t' variables never reduce their allocated space.
  1101. Normally this is the best policy, since it avoids frequent reallocation.
  1102. Applications that need to return memory to the heap at some particular
  1103. point can use 'mpz_realloc2', or clear variables no longer needed.
  1104. 'mpf_t' variables, in the current implementation, use a fixed amount
  1105. of space, determined by the chosen precision and allocated at
  1106. initialization, so their size doesn't change.
  1107. All memory is allocated using 'malloc' and friends by default, but
  1108. this can be changed, see *note Custom Allocation::. Temporary memory on
  1109. the stack is also used (via 'alloca'), but this can be changed at
  1110. build-time if desired, see *note Build Options::.
  1111. 
  1112. File: gmp.info, Node: Reentrancy, Next: Useful Macros and Constants, Prev: Memory Management, Up: GMP Basics
  1113. 3.7 Reentrancy
  1114. ==============
  1115. GMP is reentrant and thread-safe, with some exceptions:
  1116. * If configured with '--enable-alloca=malloc-notreentrant' (or with
  1117. '--enable-alloca=notreentrant' when 'alloca' is not available),
  1118. then naturally GMP is not reentrant.
  1119. * 'mpf_set_default_prec' and 'mpf_init' use a global variable for the
  1120. selected precision. 'mpf_init2' can be used instead, and in the
  1121. C++ interface an explicit precision to the 'mpf_class' constructor.
  1122. * 'mpz_random' and the other old random number functions use a global
  1123. random state and are hence not reentrant. The newer random number
  1124. functions that accept a 'gmp_randstate_t' parameter can be used
  1125. instead.
  1126. * 'gmp_randinit' (obsolete) returns an error indication through a
  1127. global variable, which is not thread safe. Applications are
  1128. advised to use 'gmp_randinit_default' or 'gmp_randinit_lc_2exp'
  1129. instead.
  1130. * 'mp_set_memory_functions' uses global variables to store the
  1131. selected memory allocation functions.
  1132. * If the memory allocation functions set by a call to
  1133. 'mp_set_memory_functions' (or 'malloc' and friends by default) are
  1134. not reentrant, then GMP will not be reentrant either.
  1135. * If the standard I/O functions such as 'fwrite' are not reentrant
  1136. then the GMP I/O functions using them will not be reentrant either.
  1137. * It's safe for two threads to read from the same GMP variable
  1138. simultaneously, but it's not safe for one to read while another
  1139. might be writing, nor for two threads to write simultaneously.
  1140. It's not safe for two threads to generate a random number from the
  1141. same 'gmp_randstate_t' simultaneously, since this involves an
  1142. update of that variable.
  1143. 
  1144. File: gmp.info, Node: Useful Macros and Constants, Next: Compatibility with older versions, Prev: Reentrancy, Up: GMP Basics
  1145. 3.8 Useful Macros and Constants
  1146. ===============================
  1147. -- Global Constant: const int mp_bits_per_limb
  1148. The number of bits per limb.
  1149. -- Macro: __GNU_MP_VERSION
  1150. -- Macro: __GNU_MP_VERSION_MINOR
  1151. -- Macro: __GNU_MP_VERSION_PATCHLEVEL
  1152. The major and minor GMP version, and patch level, respectively, as
  1153. integers. For GMP i.j, these numbers will be i, j, and 0,
  1154. respectively. For GMP i.j.k, these numbers will be i, j, and k,
  1155. respectively.
  1156. -- Global Constant: const char * const gmp_version
  1157. The GMP version number, as a null-terminated string, in the form
  1158. "i.j.k". This release is "6.1.2". Note that the format "i.j" was
  1159. used, before version 4.3.0, when k was zero.
  1160. -- Macro: __GMP_CC
  1161. -- Macro: __GMP_CFLAGS
  1162. The compiler and compiler flags, respectively, used when compiling
  1163. GMP, as strings.
  1164. 
  1165. File: gmp.info, Node: Compatibility with older versions, Next: Demonstration Programs, Prev: Useful Macros and Constants, Up: GMP Basics
  1166. 3.9 Compatibility with older versions
  1167. =====================================
  1168. This version of GMP is upwardly binary compatible with all 5.x, 4.x, and
  1169. 3.x versions, and upwardly compatible at the source level with all 2.x
  1170. versions, with the following exceptions.
  1171. * 'mpn_gcd' had its source arguments swapped as of GMP 3.0, for
  1172. consistency with other 'mpn' functions.
  1173. * 'mpf_get_prec' counted precision slightly differently in GMP 3.0
  1174. and 3.0.1, but in 3.1 reverted to the 2.x style.
  1175. * 'mpn_bdivmod', documented as preliminary in GMP 4, has been
  1176. removed.
  1177. There are a number of compatibility issues between GMP 1 and GMP 2
  1178. that of course also apply when porting applications from GMP 1 to GMP 5.
  1179. Please see the GMP 2 manual for details.
  1180. 
  1181. File: gmp.info, Node: Demonstration Programs, Next: Efficiency, Prev: Compatibility with older versions, Up: GMP Basics
  1182. 3.10 Demonstration programs
  1183. ===========================
  1184. The 'demos' subdirectory has some sample programs using GMP. These
  1185. aren't built or installed, but there's a 'Makefile' with rules for them.
  1186. For instance,
  1187. make pexpr
  1188. ./pexpr 68^975+10
  1189. The following programs are provided
  1190. * 'pexpr' is an expression evaluator, the program used on the GMP web
  1191. page.
  1192. * The 'calc' subdirectory has a similar but simpler evaluator using
  1193. 'lex' and 'yacc'.
  1194. * The 'expr' subdirectory is yet another expression evaluator, a
  1195. library designed for ease of use within a C program. See
  1196. 'demos/expr/README' for more information.
  1197. * 'factorize' is a Pollard-Rho factorization program.
  1198. * 'isprime' is a command-line interface to the 'mpz_probab_prime_p'
  1199. function.
  1200. * 'primes' counts or lists primes in an interval, using a sieve.
  1201. * 'qcn' is an example use of 'mpz_kronecker_ui' to estimate quadratic
  1202. class numbers.
  1203. * The 'perl' subdirectory is a comprehensive perl interface to GMP.
  1204. See 'demos/perl/INSTALL' for more information. Documentation is in
  1205. POD format in 'demos/perl/GMP.pm'.
  1206. As an aside, consideration has been given at various times to some
  1207. sort of expression evaluation within the main GMP library. Going beyond
  1208. something minimal quickly leads to matters like user-defined functions,
  1209. looping, fixnums for control variables, etc, which are considered
  1210. outside the scope of GMP (much closer to language interpreters or
  1211. compilers, *Note Language Bindings::.) Something simple for program
  1212. input convenience may yet be a possibility, a combination of the 'expr'
  1213. demo and the 'pexpr' tree back-end perhaps. But for now the above
  1214. evaluators are offered as illustrations.
  1215. 
  1216. File: gmp.info, Node: Efficiency, Next: Debugging, Prev: Demonstration Programs, Up: GMP Basics
  1217. 3.11 Efficiency
  1218. ===============
  1219. Small Operands
  1220. On small operands, the time for function call overheads and memory
  1221. allocation can be significant in comparison to actual calculation.
  1222. This is unavoidable in a general purpose variable precision
  1223. library, although GMP attempts to be as efficient as it can on both
  1224. large and small operands.
  1225. Static Linking
  1226. On some CPUs, in particular the x86s, the static 'libgmp.a' should
  1227. be used for maximum speed, since the PIC code in the shared
  1228. 'libgmp.so' will have a small overhead on each function call and
  1229. global data address. For many programs this will be insignificant,
  1230. but for long calculations there's a gain to be had.
  1231. Initializing and Clearing
  1232. Avoid excessive initializing and clearing of variables, since this
  1233. can be quite time consuming, especially in comparison to otherwise
  1234. fast operations like addition.
  1235. A language interpreter might want to keep a free list or stack of
  1236. initialized variables ready for use. It should be possible to
  1237. integrate something like that with a garbage collector too.
  1238. Reallocations
  1239. An 'mpz_t' or 'mpq_t' variable used to hold successively increasing
  1240. values will have its memory repeatedly 'realloc'ed, which could be
  1241. quite slow or could fragment memory, depending on the C library.
  1242. If an application can estimate the final size then 'mpz_init2' or
  1243. 'mpz_realloc2' can be called to allocate the necessary space from
  1244. the beginning (*note Initializing Integers::).
  1245. It doesn't matter if a size set with 'mpz_init2' or 'mpz_realloc2'
  1246. is too small, since all functions will do a further reallocation if
  1247. necessary. Badly overestimating memory required will waste space
  1248. though.
  1249. '2exp' Functions
  1250. It's up to an application to call functions like 'mpz_mul_2exp'
  1251. when appropriate. General purpose functions like 'mpz_mul' make no
  1252. attempt to identify powers of two or other special forms, because
  1253. such inputs will usually be very rare and testing every time would
  1254. be wasteful.
  1255. 'ui' and 'si' Functions
  1256. The 'ui' functions and the small number of 'si' functions exist for
  1257. convenience and should be used where applicable. But if for
  1258. example an 'mpz_t' contains a value that fits in an 'unsigned long'
  1259. there's no need extract it and call a 'ui' function, just use the
  1260. regular 'mpz' function.
  1261. In-Place Operations
  1262. 'mpz_abs', 'mpq_abs', 'mpf_abs', 'mpz_neg', 'mpq_neg' and 'mpf_neg'
  1263. are fast when used for in-place operations like 'mpz_abs(x,x)',
  1264. since in the current implementation only a single field of 'x'
  1265. needs changing. On suitable compilers (GCC for instance) this is
  1266. inlined too.
  1267. 'mpz_add_ui', 'mpz_sub_ui', 'mpf_add_ui' and 'mpf_sub_ui' benefit
  1268. from an in-place operation like 'mpz_add_ui(x,x,y)', since usually
  1269. only one or two limbs of 'x' will need to be changed. The same
  1270. applies to the full precision 'mpz_add' etc if 'y' is small. If
  1271. 'y' is big then cache locality may be helped, but that's all.
  1272. 'mpz_mul' is currently the opposite, a separate destination is
  1273. slightly better. A call like 'mpz_mul(x,x,y)' will, unless 'y' is
  1274. only one limb, make a temporary copy of 'x' before forming the
  1275. result. Normally that copying will only be a tiny fraction of the
  1276. time for the multiply, so this is not a particularly important
  1277. consideration.
  1278. 'mpz_set', 'mpq_set', 'mpq_set_num', 'mpf_set', etc, make no
  1279. attempt to recognise a copy of something to itself, so a call like
  1280. 'mpz_set(x,x)' will be wasteful. Naturally that would never be
  1281. written deliberately, but if it might arise from two pointers to
  1282. the same object then a test to avoid it might be desirable.
  1283. if (x != y)
  1284. mpz_set (x, y);
  1285. Note that it's never worth introducing extra 'mpz_set' calls just
  1286. to get in-place operations. If a result should go to a particular
  1287. variable then just direct it there and let GMP take care of data
  1288. movement.
  1289. Divisibility Testing (Small Integers)
  1290. 'mpz_divisible_ui_p' and 'mpz_congruent_ui_p' are the best
  1291. functions for testing whether an 'mpz_t' is divisible by an
  1292. individual small integer. They use an algorithm which is faster
  1293. than 'mpz_tdiv_ui', but which gives no useful information about the
  1294. actual remainder, only whether it's zero (or a particular value).
  1295. However when testing divisibility by several small integers, it's
  1296. best to take a remainder modulo their product, to save
  1297. multi-precision operations. For instance to test whether a number
  1298. is divisible by any of 23, 29 or 31 take a remainder modulo
  1299. 23*29*31 = 20677 and then test that.
  1300. The division functions like 'mpz_tdiv_q_ui' which give a quotient
  1301. as well as a remainder are generally a little slower than the
  1302. remainder-only functions like 'mpz_tdiv_ui'. If the quotient is
  1303. only rarely wanted then it's probably best to just take a remainder
  1304. and then go back and calculate the quotient if and when it's wanted
  1305. ('mpz_divexact_ui' can be used if the remainder is zero).
  1306. Rational Arithmetic
  1307. The 'mpq' functions operate on 'mpq_t' values with no common
  1308. factors in the numerator and denominator. Common factors are
  1309. checked-for and cast out as necessary. In general, cancelling
  1310. factors every time is the best approach since it minimizes the
  1311. sizes for subsequent operations.
  1312. However, applications that know something about the factorization
  1313. of the values they're working with might be able to avoid some of
  1314. the GCDs used for canonicalization, or swap them for divisions.
  1315. For example when multiplying by a prime it's enough to check for
  1316. factors of it in the denominator instead of doing a full GCD. Or
  1317. when forming a big product it might be known that very little
  1318. cancellation will be possible, and so canonicalization can be left
  1319. to the end.
  1320. The 'mpq_numref' and 'mpq_denref' macros give access to the
  1321. numerator and denominator to do things outside the scope of the
  1322. supplied 'mpq' functions. *Note Applying Integer Functions::.
  1323. The canonical form for rationals allows mixed-type 'mpq_t' and
  1324. integer additions or subtractions to be done directly with
  1325. multiples of the denominator. This will be somewhat faster than
  1326. 'mpq_add'. For example,
  1327. /* mpq increment */
  1328. mpz_add (mpq_numref(q), mpq_numref(q), mpq_denref(q));
  1329. /* mpq += unsigned long */
  1330. mpz_addmul_ui (mpq_numref(q), mpq_denref(q), 123UL);
  1331. /* mpq -= mpz */
  1332. mpz_submul (mpq_numref(q), mpq_denref(q), z);
  1333. Number Sequences
  1334. Functions like 'mpz_fac_ui', 'mpz_fib_ui' and 'mpz_bin_uiui' are
  1335. designed for calculating isolated values. If a range of values is
  1336. wanted it's probably best to call to get a starting point and
  1337. iterate from there.
  1338. Text Input/Output
  1339. Hexadecimal or octal are suggested for input or output in text
  1340. form. Power-of-2 bases like these can be converted much more
  1341. efficiently than other bases, like decimal. For big numbers
  1342. there's usually nothing of particular interest to be seen in the
  1343. digits, so the base doesn't matter much.
  1344. Maybe we can hope octal will one day become the normal base for
  1345. everyday use, as proposed by King Charles XII of Sweden and later
  1346. reformers.
  1347. 
  1348. File: gmp.info, Node: Debugging, Next: Profiling, Prev: Efficiency, Up: GMP Basics
  1349. 3.12 Debugging
  1350. ==============
  1351. Stack Overflow
  1352. Depending on the system, a segmentation violation or bus error
  1353. might be the only indication of stack overflow. See
  1354. '--enable-alloca' choices in *note Build Options::, for how to
  1355. address this.
  1356. In new enough versions of GCC, '-fstack-check' may be able to
  1357. ensure an overflow is recognised by the system before too much
  1358. damage is done, or '-fstack-limit-symbol' or
  1359. '-fstack-limit-register' may be able to add checking if the system
  1360. itself doesn't do any (*note Options for Code Generation: (gcc)Code
  1361. Gen Options.). These options must be added to the 'CFLAGS' used in
  1362. the GMP build (*note Build Options::), adding them just to an
  1363. application will have no effect. Note also they're a slowdown,
  1364. adding overhead to each function call and each stack allocation.
  1365. Heap Problems
  1366. The most likely cause of application problems with GMP is heap
  1367. corruption. Failing to 'init' GMP variables will have
  1368. unpredictable effects, and corruption arising elsewhere in a
  1369. program may well affect GMP. Initializing GMP variables more than
  1370. once or failing to clear them will cause memory leaks.
  1371. In all such cases a 'malloc' debugger is recommended. On a GNU or
  1372. BSD system the standard C library 'malloc' has some diagnostic
  1373. facilities, see *note Allocation Debugging: (libc)Allocation
  1374. Debugging, or 'man 3 malloc'. Other possibilities, in no
  1375. particular order, include
  1376. <http://www.inf.ethz.ch/personal/biere/projects/ccmalloc/>
  1377. <http://dmalloc.com/>
  1378. <http://www.perens.com/FreeSoftware/> (electric fence)
  1379. <http://packages.debian.org/stable/devel/fda>
  1380. <http://www.gnupdate.org/components/leakbug/>
  1381. <http://people.redhat.com/~otaylor/memprof/>
  1382. <http://www.cbmamiga.demon.co.uk/mpatrol/>
  1383. The GMP default allocation routines in 'memory.c' also have a
  1384. simple sentinel scheme which can be enabled with '#define DEBUG' in
  1385. that file. This is mainly designed for detecting buffer overruns
  1386. during GMP development, but might find other uses.
  1387. Stack Backtraces
  1388. On some systems the compiler options GMP uses by default can
  1389. interfere with debugging. In particular on x86 and 68k systems
  1390. '-fomit-frame-pointer' is used and this generally inhibits stack
  1391. backtracing. Recompiling without such options may help while
  1392. debugging, though the usual caveats about it potentially moving a
  1393. memory problem or hiding a compiler bug will apply.
  1394. GDB, the GNU Debugger
  1395. A sample '.gdbinit' is included in the distribution, showing how to
  1396. call some undocumented dump functions to print GMP variables from
  1397. within GDB. Note that these functions shouldn't be used in final
  1398. application code since they're undocumented and may be subject to
  1399. incompatible changes in future versions of GMP.
  1400. Source File Paths
  1401. GMP has multiple source files with the same name, in different
  1402. directories. For example 'mpz', 'mpq' and 'mpf' each have an
  1403. 'init.c'. If the debugger can't already determine the right one it
  1404. may help to build with absolute paths on each C file. One way to
  1405. do that is to use a separate object directory with an absolute path
  1406. to the source directory.
  1407. cd /my/build/dir
  1408. /my/source/dir/gmp-6.1.2/configure
  1409. This works via 'VPATH', and might require GNU 'make'. Alternately
  1410. it might be possible to change the '.c.lo' rules appropriately.
  1411. Assertion Checking
  1412. The build option '--enable-assert' is available to add some
  1413. consistency checks to the library (see *note Build Options::).
  1414. These are likely to be of limited value to most applications.
  1415. Assertion failures are just as likely to indicate memory corruption
  1416. as a library or compiler bug.
  1417. Applications using the low-level 'mpn' functions, however, will
  1418. benefit from '--enable-assert' since it adds checks on the
  1419. parameters of most such functions, many of which have subtle
  1420. restrictions on their usage. Note however that only the generic C
  1421. code has checks, not the assembly code, so '--disable-assembly'
  1422. should be used for maximum checking.
  1423. Temporary Memory Checking
  1424. The build option '--enable-alloca=debug' arranges that each block
  1425. of temporary memory in GMP is allocated with a separate call to
  1426. 'malloc' (or the allocation function set with
  1427. 'mp_set_memory_functions').
  1428. This can help a malloc debugger detect accesses outside the
  1429. intended bounds, or detect memory not released. In a normal build,
  1430. on the other hand, temporary memory is allocated in blocks which
  1431. GMP divides up for its own use, or may be allocated with a compiler
  1432. builtin 'alloca' which will go nowhere near any malloc debugger
  1433. hooks.
  1434. Maximum Debuggability
  1435. To summarize the above, a GMP build for maximum debuggability would
  1436. be
  1437. ./configure --disable-shared --enable-assert \
  1438. --enable-alloca=debug --disable-assembly CFLAGS=-g
  1439. For C++, add '--enable-cxx CXXFLAGS=-g'.
  1440. Checker
  1441. The GCC checker (<https://savannah.nongnu.org/projects/checker/>)
  1442. can be used with GMP. It contains a stub library which means GMP
  1443. applications compiled with checker can use a normal GMP build.
  1444. A build of GMP with checking within GMP itself can be made. This
  1445. will run very very slowly. On GNU/Linux for example,
  1446. ./configure --disable-assembly CC=checkergcc
  1447. '--disable-assembly' must be used, since the GMP assembly code
  1448. doesn't support the checking scheme. The GMP C++ features cannot
  1449. be used, since current versions of checker (0.9.9.1) don't yet
  1450. support the standard C++ library.
  1451. Valgrind
  1452. Valgrind (<http://valgrind.org/>) is a memory checker for x86, ARM,
  1453. MIPS, PowerPC, and S/390. It translates and emulates machine
  1454. instructions to do strong checks for uninitialized data (at the
  1455. level of individual bits), memory accesses through bad pointers,
  1456. and memory leaks.
  1457. Valgrind does not always support every possible instruction, in
  1458. particular ones recently added to an ISA. Valgrind might therefore
  1459. be incompatible with a recent GMP or even a less recent GMP which
  1460. is compiled using a recent GCC.
  1461. GMP's assembly code sometimes promotes a read of the limbs to some
  1462. larger size, for efficiency. GMP will do this even at the start
  1463. and end of a multilimb operand, using naturally aligned operations
  1464. on the larger type. This may lead to benign reads outside of
  1465. allocated areas, triggering complaints from Valgrind. Valgrind's
  1466. option '--partial-loads-ok=yes' should help.
  1467. Other Problems
  1468. Any suspected bug in GMP itself should be isolated to make sure
  1469. it's not an application problem, see *note Reporting Bugs::.
  1470. 
  1471. File: gmp.info, Node: Profiling, Next: Autoconf, Prev: Debugging, Up: GMP Basics
  1472. 3.13 Profiling
  1473. ==============
  1474. Running a program under a profiler is a good way to find where it's
  1475. spending most time and where improvements can be best sought. The
  1476. profiling choices for a GMP build are as follows.
  1477. '--disable-profiling'
  1478. The default is to add nothing special for profiling.
  1479. It should be possible to just compile the mainline of a program
  1480. with '-p' and use 'prof' to get a profile consisting of timer-based
  1481. sampling of the program counter. Most of the GMP assembly code has
  1482. the necessary symbol information.
  1483. This approach has the advantage of minimizing interference with
  1484. normal program operation, but on most systems the resolution of the
  1485. sampling is quite low (10 milliseconds for instance), requiring
  1486. long runs to get accurate information.
  1487. '--enable-profiling=prof'
  1488. Build with support for the system 'prof', which means '-p' added to
  1489. the 'CFLAGS'.
  1490. This provides call counting in addition to program counter
  1491. sampling, which allows the most frequently called routines to be
  1492. identified, and an average time spent in each routine to be
  1493. determined.
  1494. The x86 assembly code has support for this option, but on other
  1495. processors the assembly routines will be as if compiled without
  1496. '-p' and therefore won't appear in the call counts.
  1497. On some systems, such as GNU/Linux, '-p' in fact means '-pg' and in
  1498. this case '--enable-profiling=gprof' described below should be used
  1499. instead.
  1500. '--enable-profiling=gprof'
  1501. Build with support for 'gprof', which means '-pg' added to the
  1502. 'CFLAGS'.
  1503. This provides call graph construction in addition to call counting
  1504. and program counter sampling, which makes it possible to count
  1505. calls coming from different locations. For example the number of
  1506. calls to 'mpn_mul' from 'mpz_mul' versus the number from 'mpf_mul'.
  1507. The program counter sampling is still flat though, so only a total
  1508. time in 'mpn_mul' would be accumulated, not a separate amount for
  1509. each call site.
  1510. The x86 assembly code has support for this option, but on other
  1511. processors the assembly routines will be as if compiled without
  1512. '-pg' and therefore not be included in the call counts.
  1513. On x86 and m68k systems '-pg' and '-fomit-frame-pointer' are
  1514. incompatible, so the latter is omitted from the default flags in
  1515. that case, which might result in poorer code generation.
  1516. Incidentally, it should be possible to use the 'gprof' program with
  1517. a plain '--enable-profiling=prof' build. But in that case only the
  1518. 'gprof -p' flat profile and call counts can be expected to be
  1519. valid, not the 'gprof -q' call graph.
  1520. '--enable-profiling=instrument'
  1521. Build with the GCC option '-finstrument-functions' added to the
  1522. 'CFLAGS' (*note Options for Code Generation: (gcc)Code Gen
  1523. Options.).
  1524. This inserts special instrumenting calls at the start and end of
  1525. each function, allowing exact timing and full call graph
  1526. construction.
  1527. This instrumenting is not normally a standard system feature and
  1528. will require support from an external library, such as
  1529. <http://sourceforge.net/projects/fnccheck/>
  1530. This should be included in 'LIBS' during the GMP configure so that
  1531. test programs will link. For example,
  1532. ./configure --enable-profiling=instrument LIBS=-lfc
  1533. On a GNU system the C library provides dummy instrumenting
  1534. functions, so programs compiled with this option will link. In
  1535. this case it's only necessary to ensure the correct library is
  1536. added when linking an application.
  1537. The x86 assembly code supports this option, but on other processors
  1538. the assembly routines will be as if compiled without
  1539. '-finstrument-functions' meaning time spent in them will
  1540. effectively be attributed to their caller.
  1541. 
  1542. File: gmp.info, Node: Autoconf, Next: Emacs, Prev: Profiling, Up: GMP Basics
  1543. 3.14 Autoconf
  1544. =============
  1545. Autoconf based applications can easily check whether GMP is installed.
  1546. The only thing to be noted is that GMP library symbols from version 3
  1547. onwards have prefixes like '__gmpz'. The following therefore would be a
  1548. simple test,
  1549. AC_CHECK_LIB(gmp, __gmpz_init)
  1550. This just uses the default 'AC_CHECK_LIB' actions for found or not
  1551. found, but an application that must have GMP would want to generate an
  1552. error if not found. For example,
  1553. AC_CHECK_LIB(gmp, __gmpz_init, ,
  1554. [AC_MSG_ERROR([GNU MP not found, see https://gmplib.org/])])
  1555. If functions added in some particular version of GMP are required,
  1556. then one of those can be used when checking. For example 'mpz_mul_si'
  1557. was added in GMP 3.1,
  1558. AC_CHECK_LIB(gmp, __gmpz_mul_si, ,
  1559. [AC_MSG_ERROR(
  1560. [GNU MP not found, or not 3.1 or up, see https://gmplib.org/])])
  1561. An alternative would be to test the version number in 'gmp.h' using
  1562. say 'AC_EGREP_CPP'. That would make it possible to test the exact
  1563. version, if some particular sub-minor release is known to be necessary.
  1564. In general it's recommended that applications should simply demand a
  1565. new enough GMP rather than trying to provide supplements for features
  1566. not available in past versions.
  1567. Occasionally an application will need or want to know the size of a
  1568. type at configuration or preprocessing time, not just with 'sizeof' in
  1569. the code. This can be done in the normal way with 'mp_limb_t' etc, but
  1570. GMP 4.0 or up is best for this, since prior versions needed certain '-D'
  1571. defines on systems using a 'long long' limb. The following would suit
  1572. Autoconf 2.50 or up,
  1573. AC_CHECK_SIZEOF(mp_limb_t, , [#include <gmp.h>])
  1574. 
  1575. File: gmp.info, Node: Emacs, Prev: Autoconf, Up: GMP Basics
  1576. 3.15 Emacs
  1577. ==========
  1578. <C-h C-i> ('info-lookup-symbol') is a good way to find documentation on
  1579. C functions while editing (*note Info Documentation Lookup: (emacs)Info
  1580. Lookup.).
  1581. The GMP manual can be included in such lookups by putting the
  1582. following in your '.emacs',
  1583. (eval-after-load "info-look"
  1584. '(let ((mode-value (assoc 'c-mode (assoc 'symbol info-lookup-alist))))
  1585. (setcar (nthcdr 3 mode-value)
  1586. (cons '("(gmp)Function Index" nil "^ -.* " "\\>")
  1587. (nth 3 mode-value)))))
  1588. 
  1589. File: gmp.info, Node: Reporting Bugs, Next: Integer Functions, Prev: GMP Basics, Up: Top
  1590. 4 Reporting Bugs
  1591. ****************
  1592. If you think you have found a bug in the GMP library, please investigate
  1593. it and report it. We have made this library available to you, and it is
  1594. not too much to ask you to report the bugs you find.
  1595. Before you report a bug, check it's not already addressed in *note
  1596. Known Build Problems::, or perhaps *note Notes for Particular Systems::.
  1597. You may also want to check <https://gmplib.org/> for patches for this
  1598. release.
  1599. Please include the following in any report,
  1600. * The GMP version number, and if pre-packaged or patched then say so.
  1601. * A test program that makes it possible for us to reproduce the bug.
  1602. Include instructions on how to run the program.
  1603. * A description of what is wrong. If the results are incorrect, in
  1604. what way. If you get a crash, say so.
  1605. * If you get a crash, include a stack backtrace from the debugger if
  1606. it's informative ('where' in 'gdb', or '$C' in 'adb').
  1607. * Please do not send core dumps, executables or 'strace's.
  1608. * The 'configure' options you used when building GMP, if any.
  1609. * The output from 'configure', as printed to stdout, with any options
  1610. used.
  1611. * The name of the compiler and its version. For 'gcc', get the
  1612. version with 'gcc -v', otherwise perhaps 'what `which cc`', or
  1613. similar.
  1614. * The output from running 'uname -a'.
  1615. * The output from running './config.guess', and from running
  1616. './configfsf.guess' (might be the same).
  1617. * If the bug is related to 'configure', then the compressed contents
  1618. of 'config.log'.
  1619. * If the bug is related to an 'asm' file not assembling, then the
  1620. contents of 'config.m4' and the offending line or lines from the
  1621. temporary 'mpn/tmp-<file>.s'.
  1622. Please make an effort to produce a self-contained report, with
  1623. something definite that can be tested or debugged. Vague queries or
  1624. piecemeal messages are difficult to act on and don't help the
  1625. development effort.
  1626. It is not uncommon that an observed problem is actually due to a bug
  1627. in the compiler; the GMP code tends to explore interesting corners in
  1628. compilers.
  1629. If your bug report is good, we will do our best to help you get a
  1630. corrected version of the library; if the bug report is poor, we won't do
  1631. anything about it (except maybe ask you to send a better report).
  1632. Send your report to: <gmp-bugs@gmplib.org>.
  1633. If you think something in this manual is unclear, or downright
  1634. incorrect, or if the language needs to be improved, please send a note
  1635. to the same address.
  1636. 
  1637. File: gmp.info, Node: Integer Functions, Next: Rational Number Functions, Prev: Reporting Bugs, Up: Top
  1638. 5 Integer Functions
  1639. *******************
  1640. This chapter describes the GMP functions for performing integer
  1641. arithmetic. These functions start with the prefix 'mpz_'.
  1642. GMP integers are stored in objects of type 'mpz_t'.
  1643. * Menu:
  1644. * Initializing Integers::
  1645. * Assigning Integers::
  1646. * Simultaneous Integer Init & Assign::
  1647. * Converting Integers::
  1648. * Integer Arithmetic::
  1649. * Integer Division::
  1650. * Integer Exponentiation::
  1651. * Integer Roots::
  1652. * Number Theoretic Functions::
  1653. * Integer Comparisons::
  1654. * Integer Logic and Bit Fiddling::
  1655. * I/O of Integers::
  1656. * Integer Random Numbers::
  1657. * Integer Import and Export::
  1658. * Miscellaneous Integer Functions::
  1659. * Integer Special Functions::
  1660. 
  1661. File: gmp.info, Node: Initializing Integers, Next: Assigning Integers, Prev: Integer Functions, Up: Integer Functions
  1662. 5.1 Initialization Functions
  1663. ============================
  1664. The functions for integer arithmetic assume that all integer objects are
  1665. initialized. You do that by calling the function 'mpz_init'. For
  1666. example,
  1667. {
  1668. mpz_t integ;
  1669. mpz_init (integ);
  1670. ...
  1671. mpz_add (integ, ...);
  1672. ...
  1673. mpz_sub (integ, ...);
  1674. /* Unless the program is about to exit, do ... */
  1675. mpz_clear (integ);
  1676. }
  1677. As you can see, you can store new values any number of times, once an
  1678. object is initialized.
  1679. -- Function: void mpz_init (mpz_t X)
  1680. Initialize X, and set its value to 0.
  1681. -- Function: void mpz_inits (mpz_t X, ...)
  1682. Initialize a NULL-terminated list of 'mpz_t' variables, and set
  1683. their values to 0.
  1684. -- Function: void mpz_init2 (mpz_t X, mp_bitcnt_t N)
  1685. Initialize X, with space for N-bit numbers, and set its value to 0.
  1686. Calling this function instead of 'mpz_init' or 'mpz_inits' is never
  1687. necessary; reallocation is handled automatically by GMP when
  1688. needed.
  1689. While N defines the initial space, X will grow automatically in the
  1690. normal way, if necessary, for subsequent values stored.
  1691. 'mpz_init2' makes it possible to avoid such reallocations if a
  1692. maximum size is known in advance.
  1693. In preparation for an operation, GMP often allocates one limb more
  1694. than ultimately needed. To make sure GMP will not perform
  1695. reallocation for X, you need to add the number of bits in
  1696. 'mp_limb_t' to N.
  1697. -- Function: void mpz_clear (mpz_t X)
  1698. Free the space occupied by X. Call this function for all 'mpz_t'
  1699. variables when you are done with them.
  1700. -- Function: void mpz_clears (mpz_t X, ...)
  1701. Free the space occupied by a NULL-terminated list of 'mpz_t'
  1702. variables.
  1703. -- Function: void mpz_realloc2 (mpz_t X, mp_bitcnt_t N)
  1704. Change the space allocated for X to N bits. The value in X is
  1705. preserved if it fits, or is set to 0 if not.
  1706. Calling this function is never necessary; reallocation is handled
  1707. automatically by GMP when needed. But this function can be used to
  1708. increase the space for a variable in order to avoid repeated
  1709. automatic reallocations, or to decrease it to give memory back to
  1710. the heap.
  1711. 
  1712. File: gmp.info, Node: Assigning Integers, Next: Simultaneous Integer Init & Assign, Prev: Initializing Integers, Up: Integer Functions
  1713. 5.2 Assignment Functions
  1714. ========================
  1715. These functions assign new values to already initialized integers (*note
  1716. Initializing Integers::).
  1717. -- Function: void mpz_set (mpz_t ROP, const mpz_t OP)
  1718. -- Function: void mpz_set_ui (mpz_t ROP, unsigned long int OP)
  1719. -- Function: void mpz_set_si (mpz_t ROP, signed long int OP)
  1720. -- Function: void mpz_set_d (mpz_t ROP, double OP)
  1721. -- Function: void mpz_set_q (mpz_t ROP, const mpq_t OP)
  1722. -- Function: void mpz_set_f (mpz_t ROP, const mpf_t OP)
  1723. Set the value of ROP from OP.
  1724. 'mpz_set_d', 'mpz_set_q' and 'mpz_set_f' truncate OP to make it an
  1725. integer.
  1726. -- Function: int mpz_set_str (mpz_t ROP, const char *STR, int BASE)
  1727. Set the value of ROP from STR, a null-terminated C string in base
  1728. BASE. White space is allowed in the string, and is simply ignored.
  1729. The BASE may vary from 2 to 62, or if BASE is 0, then the leading
  1730. characters are used: '0x' and '0X' for hexadecimal, '0b' and '0B'
  1731. for binary, '0' for octal, or decimal otherwise.
  1732. For bases up to 36, case is ignored; upper-case and lower-case
  1733. letters have the same value. For bases 37 to 62, upper-case letter
  1734. represent the usual 10..35 while lower-case letter represent
  1735. 36..61.
  1736. This function returns 0 if the entire string is a valid number in
  1737. base BASE. Otherwise it returns -1.
  1738. -- Function: void mpz_swap (mpz_t ROP1, mpz_t ROP2)
  1739. Swap the values ROP1 and ROP2 efficiently.
  1740. 
  1741. File: gmp.info, Node: Simultaneous Integer Init & Assign, Next: Converting Integers, Prev: Assigning Integers, Up: Integer Functions
  1742. 5.3 Combined Initialization and Assignment Functions
  1743. ====================================================
  1744. For convenience, GMP provides a parallel series of initialize-and-set
  1745. functions which initialize the output and then store the value there.
  1746. These functions' names have the form 'mpz_init_set...'
  1747. Here is an example of using one:
  1748. {
  1749. mpz_t pie;
  1750. mpz_init_set_str (pie, "3141592653589793238462643383279502884", 10);
  1751. ...
  1752. mpz_sub (pie, ...);
  1753. ...
  1754. mpz_clear (pie);
  1755. }
  1756. Once the integer has been initialized by any of the 'mpz_init_set...'
  1757. functions, it can be used as the source or destination operand for the
  1758. ordinary integer functions. Don't use an initialize-and-set function on
  1759. a variable already initialized!
  1760. -- Function: void mpz_init_set (mpz_t ROP, const mpz_t OP)
  1761. -- Function: void mpz_init_set_ui (mpz_t ROP, unsigned long int OP)
  1762. -- Function: void mpz_init_set_si (mpz_t ROP, signed long int OP)
  1763. -- Function: void mpz_init_set_d (mpz_t ROP, double OP)
  1764. Initialize ROP with limb space and set the initial numeric value
  1765. from OP.
  1766. -- Function: int mpz_init_set_str (mpz_t ROP, const char *STR, int
  1767. BASE)
  1768. Initialize ROP and set its value like 'mpz_set_str' (see its
  1769. documentation above for details).
  1770. If the string is a correct base BASE number, the function returns
  1771. 0; if an error occurs it returns -1. ROP is initialized even if an
  1772. error occurs. (I.e., you have to call 'mpz_clear' for it.)
  1773. 
  1774. File: gmp.info, Node: Converting Integers, Next: Integer Arithmetic, Prev: Simultaneous Integer Init & Assign, Up: Integer Functions
  1775. 5.4 Conversion Functions
  1776. ========================
  1777. This section describes functions for converting GMP integers to standard
  1778. C types. Functions for converting _to_ GMP integers are described in
  1779. *note Assigning Integers:: and *note I/O of Integers::.
  1780. -- Function: unsigned long int mpz_get_ui (const mpz_t OP)
  1781. Return the value of OP as an 'unsigned long'.
  1782. If OP is too big to fit an 'unsigned long' then just the least
  1783. significant bits that do fit are returned. The sign of OP is
  1784. ignored, only the absolute value is used.
  1785. -- Function: signed long int mpz_get_si (const mpz_t OP)
  1786. If OP fits into a 'signed long int' return the value of OP.
  1787. Otherwise return the least significant part of OP, with the same
  1788. sign as OP.
  1789. If OP is too big to fit in a 'signed long int', the returned result
  1790. is probably not very useful. To find out if the value will fit,
  1791. use the function 'mpz_fits_slong_p'.
  1792. -- Function: double mpz_get_d (const mpz_t OP)
  1793. Convert OP to a 'double', truncating if necessary (i.e. rounding
  1794. towards zero).
  1795. If the exponent from the conversion is too big, the result is
  1796. system dependent. An infinity is returned where available. A
  1797. hardware overflow trap may or may not occur.
  1798. -- Function: double mpz_get_d_2exp (signed long int *EXP, const mpz_t
  1799. OP)
  1800. Convert OP to a 'double', truncating if necessary (i.e. rounding
  1801. towards zero), and returning the exponent separately.
  1802. The return value is in the range 0.5<=abs(D)<1 and the exponent is
  1803. stored to '*EXP'. D * 2^EXP is the (truncated) OP value. If OP is
  1804. zero, the return is 0.0 and 0 is stored to '*EXP'.
  1805. This is similar to the standard C 'frexp' function (*note
  1806. (libc)Normalization Functions::).
  1807. -- Function: char * mpz_get_str (char *STR, int BASE, const mpz_t OP)
  1808. Convert OP to a string of digits in base BASE. The base argument
  1809. may vary from 2 to 62 or from -2 to -36.
  1810. For BASE in the range 2..36, digits and lower-case letters are
  1811. used; for -2..-36, digits and upper-case letters are used; for
  1812. 37..62, digits, upper-case letters, and lower-case letters (in that
  1813. significance order) are used.
  1814. If STR is 'NULL', the result string is allocated using the current
  1815. allocation function (*note Custom Allocation::). The block will be
  1816. 'strlen(str)+1' bytes, that being exactly enough for the string and
  1817. null-terminator.
  1818. If STR is not 'NULL', it should point to a block of storage large
  1819. enough for the result, that being 'mpz_sizeinbase (OP, BASE) + 2'.
  1820. The two extra bytes are for a possible minus sign, and the
  1821. null-terminator.
  1822. A pointer to the result string is returned, being either the
  1823. allocated block, or the given STR.
  1824. 
  1825. File: gmp.info, Node: Integer Arithmetic, Next: Integer Division, Prev: Converting Integers, Up: Integer Functions
  1826. 5.5 Arithmetic Functions
  1827. ========================
  1828. -- Function: void mpz_add (mpz_t ROP, const mpz_t OP1, const mpz_t OP2)
  1829. -- Function: void mpz_add_ui (mpz_t ROP, const mpz_t OP1, unsigned long
  1830. int OP2)
  1831. Set ROP to OP1 + OP2.
  1832. -- Function: void mpz_sub (mpz_t ROP, const mpz_t OP1, const mpz_t OP2)
  1833. -- Function: void mpz_sub_ui (mpz_t ROP, const mpz_t OP1, unsigned long
  1834. int OP2)
  1835. -- Function: void mpz_ui_sub (mpz_t ROP, unsigned long int OP1, const
  1836. mpz_t OP2)
  1837. Set ROP to OP1 - OP2.
  1838. -- Function: void mpz_mul (mpz_t ROP, const mpz_t OP1, const mpz_t OP2)
  1839. -- Function: void mpz_mul_si (mpz_t ROP, const mpz_t OP1, long int OP2)
  1840. -- Function: void mpz_mul_ui (mpz_t ROP, const mpz_t OP1, unsigned long
  1841. int OP2)
  1842. Set ROP to OP1 times OP2.
  1843. -- Function: void mpz_addmul (mpz_t ROP, const mpz_t OP1, const mpz_t
  1844. OP2)
  1845. -- Function: void mpz_addmul_ui (mpz_t ROP, const mpz_t OP1, unsigned
  1846. long int OP2)
  1847. Set ROP to ROP + OP1 times OP2.
  1848. -- Function: void mpz_submul (mpz_t ROP, const mpz_t OP1, const mpz_t
  1849. OP2)
  1850. -- Function: void mpz_submul_ui (mpz_t ROP, const mpz_t OP1, unsigned
  1851. long int OP2)
  1852. Set ROP to ROP - OP1 times OP2.
  1853. -- Function: void mpz_mul_2exp (mpz_t ROP, const mpz_t OP1, mp_bitcnt_t
  1854. OP2)
  1855. Set ROP to OP1 times 2 raised to OP2. This operation can also be
  1856. defined as a left shift by OP2 bits.
  1857. -- Function: void mpz_neg (mpz_t ROP, const mpz_t OP)
  1858. Set ROP to -OP.
  1859. -- Function: void mpz_abs (mpz_t ROP, const mpz_t OP)
  1860. Set ROP to the absolute value of OP.
  1861. 
  1862. File: gmp.info, Node: Integer Division, Next: Integer Exponentiation, Prev: Integer Arithmetic, Up: Integer Functions
  1863. 5.6 Division Functions
  1864. ======================
  1865. Division is undefined if the divisor is zero. Passing a zero divisor to
  1866. the division or modulo functions (including the modular powering
  1867. functions 'mpz_powm' and 'mpz_powm_ui'), will cause an intentional
  1868. division by zero. This lets a program handle arithmetic exceptions in
  1869. these functions the same way as for normal C 'int' arithmetic.
  1870. -- Function: void mpz_cdiv_q (mpz_t Q, const mpz_t N, const mpz_t D)
  1871. -- Function: void mpz_cdiv_r (mpz_t R, const mpz_t N, const mpz_t D)
  1872. -- Function: void mpz_cdiv_qr (mpz_t Q, mpz_t R, const mpz_t N, const
  1873. mpz_t D)
  1874. -- Function: unsigned long int mpz_cdiv_q_ui (mpz_t Q, const mpz_t N,
  1875. unsigned long int D)
  1876. -- Function: unsigned long int mpz_cdiv_r_ui (mpz_t R, const mpz_t N,
  1877. unsigned long int D)
  1878. -- Function: unsigned long int mpz_cdiv_qr_ui (mpz_t Q, mpz_t R,
  1879. const mpz_t N, unsigned long int D)
  1880. -- Function: unsigned long int mpz_cdiv_ui (const mpz_t N,
  1881. unsigned long int D)
  1882. -- Function: void mpz_cdiv_q_2exp (mpz_t Q, const mpz_t N,
  1883. mp_bitcnt_t B)
  1884. -- Function: void mpz_cdiv_r_2exp (mpz_t R, const mpz_t N,
  1885. mp_bitcnt_t B)
  1886. -- Function: void mpz_fdiv_q (mpz_t Q, const mpz_t N, const mpz_t D)
  1887. -- Function: void mpz_fdiv_r (mpz_t R, const mpz_t N, const mpz_t D)
  1888. -- Function: void mpz_fdiv_qr (mpz_t Q, mpz_t R, const mpz_t N, const
  1889. mpz_t D)
  1890. -- Function: unsigned long int mpz_fdiv_q_ui (mpz_t Q, const mpz_t N,
  1891. unsigned long int D)
  1892. -- Function: unsigned long int mpz_fdiv_r_ui (mpz_t R, const mpz_t N,
  1893. unsigned long int D)
  1894. -- Function: unsigned long int mpz_fdiv_qr_ui (mpz_t Q, mpz_t R,
  1895. const mpz_t N, unsigned long int D)
  1896. -- Function: unsigned long int mpz_fdiv_ui (const mpz_t N,
  1897. unsigned long int D)
  1898. -- Function: void mpz_fdiv_q_2exp (mpz_t Q, const mpz_t N,
  1899. mp_bitcnt_t B)
  1900. -- Function: void mpz_fdiv_r_2exp (mpz_t R, const mpz_t N,
  1901. mp_bitcnt_t B)
  1902. -- Function: void mpz_tdiv_q (mpz_t Q, const mpz_t N, const mpz_t D)
  1903. -- Function: void mpz_tdiv_r (mpz_t R, const mpz_t N, const mpz_t D)
  1904. -- Function: void mpz_tdiv_qr (mpz_t Q, mpz_t R, const mpz_t N, const
  1905. mpz_t D)
  1906. -- Function: unsigned long int mpz_tdiv_q_ui (mpz_t Q, const mpz_t N,
  1907. unsigned long int D)
  1908. -- Function: unsigned long int mpz_tdiv_r_ui (mpz_t R, const mpz_t N,
  1909. unsigned long int D)
  1910. -- Function: unsigned long int mpz_tdiv_qr_ui (mpz_t Q, mpz_t R,
  1911. const mpz_t N, unsigned long int D)
  1912. -- Function: unsigned long int mpz_tdiv_ui (const mpz_t N,
  1913. unsigned long int D)
  1914. -- Function: void mpz_tdiv_q_2exp (mpz_t Q, const mpz_t N,
  1915. mp_bitcnt_t B)
  1916. -- Function: void mpz_tdiv_r_2exp (mpz_t R, const mpz_t N,
  1917. mp_bitcnt_t B)
  1918. Divide N by D, forming a quotient Q and/or remainder R. For the
  1919. '2exp' functions, D=2^B. The rounding is in three styles, each
  1920. suiting different applications.
  1921. * 'cdiv' rounds Q up towards +infinity, and R will have the
  1922. opposite sign to D. The 'c' stands for "ceil".
  1923. * 'fdiv' rounds Q down towards -infinity, and R will have the
  1924. same sign as D. The 'f' stands for "floor".
  1925. * 'tdiv' rounds Q towards zero, and R will have the same sign as
  1926. N. The 't' stands for "truncate".
  1927. In all cases Q and R will satisfy N=Q*D+R, and R will satisfy
  1928. 0<=abs(R)<abs(D).
  1929. The 'q' functions calculate only the quotient, the 'r' functions
  1930. only the remainder, and the 'qr' functions calculate both. Note
  1931. that for 'qr' the same variable cannot be passed for both Q and R,
  1932. or results will be unpredictable.
  1933. For the 'ui' variants the return value is the remainder, and in
  1934. fact returning the remainder is all the 'div_ui' functions do. For
  1935. 'tdiv' and 'cdiv' the remainder can be negative, so for those the
  1936. return value is the absolute value of the remainder.
  1937. For the '2exp' variants the divisor is 2^B. These functions are
  1938. implemented as right shifts and bit masks, but of course they round
  1939. the same as the other functions.
  1940. For positive N both 'mpz_fdiv_q_2exp' and 'mpz_tdiv_q_2exp' are
  1941. simple bitwise right shifts. For negative N, 'mpz_fdiv_q_2exp' is
  1942. effectively an arithmetic right shift treating N as twos complement
  1943. the same as the bitwise logical functions do, whereas
  1944. 'mpz_tdiv_q_2exp' effectively treats N as sign and magnitude.
  1945. -- Function: void mpz_mod (mpz_t R, const mpz_t N, const mpz_t D)
  1946. -- Function: unsigned long int mpz_mod_ui (mpz_t R, const mpz_t N,
  1947. unsigned long int D)
  1948. Set R to N 'mod' D. The sign of the divisor is ignored; the result
  1949. is always non-negative.
  1950. 'mpz_mod_ui' is identical to 'mpz_fdiv_r_ui' above, returning the
  1951. remainder as well as setting R. See 'mpz_fdiv_ui' above if only
  1952. the return value is wanted.
  1953. -- Function: void mpz_divexact (mpz_t Q, const mpz_t N, const mpz_t D)
  1954. -- Function: void mpz_divexact_ui (mpz_t Q, const mpz_t N, unsigned
  1955. long D)
  1956. Set Q to N/D. These functions produce correct results only when it
  1957. is known in advance that D divides N.
  1958. These routines are much faster than the other division functions,
  1959. and are the best choice when exact division is known to occur, for
  1960. example reducing a rational to lowest terms.
  1961. -- Function: int mpz_divisible_p (const mpz_t N, const mpz_t D)
  1962. -- Function: int mpz_divisible_ui_p (const mpz_t N, unsigned long int
  1963. D)
  1964. -- Function: int mpz_divisible_2exp_p (const mpz_t N, mp_bitcnt_t B)
  1965. Return non-zero if N is exactly divisible by D, or in the case of
  1966. 'mpz_divisible_2exp_p' by 2^B.
  1967. N is divisible by D if there exists an integer Q satisfying N =
  1968. Q*D. Unlike the other division functions, D=0 is accepted and
  1969. following the rule it can be seen that only 0 is considered
  1970. divisible by 0.
  1971. -- Function: int mpz_congruent_p (const mpz_t N, const mpz_t C, const
  1972. mpz_t D)
  1973. -- Function: int mpz_congruent_ui_p (const mpz_t N, unsigned long int
  1974. C, unsigned long int D)
  1975. -- Function: int mpz_congruent_2exp_p (const mpz_t N, const mpz_t C,
  1976. mp_bitcnt_t B)
  1977. Return non-zero if N is congruent to C modulo D, or in the case of
  1978. 'mpz_congruent_2exp_p' modulo 2^B.
  1979. N is congruent to C mod D if there exists an integer Q satisfying N
  1980. = C + Q*D. Unlike the other division functions, D=0 is accepted
  1981. and following the rule it can be seen that N and C are considered
  1982. congruent mod 0 only when exactly equal.
  1983. 
  1984. File: gmp.info, Node: Integer Exponentiation, Next: Integer Roots, Prev: Integer Division, Up: Integer Functions
  1985. 5.7 Exponentiation Functions
  1986. ============================
  1987. -- Function: void mpz_powm (mpz_t ROP, const mpz_t BASE, const mpz_t
  1988. EXP, const mpz_t MOD)
  1989. -- Function: void mpz_powm_ui (mpz_t ROP, const mpz_t BASE, unsigned
  1990. long int EXP, const mpz_t MOD)
  1991. Set ROP to (BASE raised to EXP) modulo MOD.
  1992. Negative EXP is supported if an inverse BASE^-1 mod MOD exists (see
  1993. 'mpz_invert' in *note Number Theoretic Functions::). If an inverse
  1994. doesn't exist then a divide by zero is raised.
  1995. -- Function: void mpz_powm_sec (mpz_t ROP, const mpz_t BASE, const
  1996. mpz_t EXP, const mpz_t MOD)
  1997. Set ROP to (BASE raised to EXP) modulo MOD.
  1998. It is required that EXP > 0 and that MOD is odd.
  1999. This function is designed to take the same time and have the same
  2000. cache access patterns for any two same-size arguments, assuming
  2001. that function arguments are placed at the same position and that
  2002. the machine state is identical upon function entry. This function
  2003. is intended for cryptographic purposes, where resilience to
  2004. side-channel attacks is desired.
  2005. -- Function: void mpz_pow_ui (mpz_t ROP, const mpz_t BASE, unsigned
  2006. long int EXP)
  2007. -- Function: void mpz_ui_pow_ui (mpz_t ROP, unsigned long int BASE,
  2008. unsigned long int EXP)
  2009. Set ROP to BASE raised to EXP. The case 0^0 yields 1.
  2010. 
  2011. File: gmp.info, Node: Integer Roots, Next: Number Theoretic Functions, Prev: Integer Exponentiation, Up: Integer Functions
  2012. 5.8 Root Extraction Functions
  2013. =============================
  2014. -- Function: int mpz_root (mpz_t ROP, const mpz_t OP, unsigned long int
  2015. N)
  2016. Set ROP to the truncated integer part of the Nth root of OP.
  2017. Return non-zero if the computation was exact, i.e., if OP is ROP to
  2018. the Nth power.
  2019. -- Function: void mpz_rootrem (mpz_t ROOT, mpz_t REM, const mpz_t U,
  2020. unsigned long int N)
  2021. Set ROOT to the truncated integer part of the Nth root of U. Set
  2022. REM to the remainder, U-ROOT**N.
  2023. -- Function: void mpz_sqrt (mpz_t ROP, const mpz_t OP)
  2024. Set ROP to the truncated integer part of the square root of OP.
  2025. -- Function: void mpz_sqrtrem (mpz_t ROP1, mpz_t ROP2, const mpz_t OP)
  2026. Set ROP1 to the truncated integer part of the square root of OP,
  2027. like 'mpz_sqrt'. Set ROP2 to the remainder OP-ROP1*ROP1, which
  2028. will be zero if OP is a perfect square.
  2029. If ROP1 and ROP2 are the same variable, the results are undefined.
  2030. -- Function: int mpz_perfect_power_p (const mpz_t OP)
  2031. Return non-zero if OP is a perfect power, i.e., if there exist
  2032. integers A and B, with B>1, such that OP equals A raised to the
  2033. power B.
  2034. Under this definition both 0 and 1 are considered to be perfect
  2035. powers. Negative values of OP are accepted, but of course can only
  2036. be odd perfect powers.
  2037. -- Function: int mpz_perfect_square_p (const mpz_t OP)
  2038. Return non-zero if OP is a perfect square, i.e., if the square root
  2039. of OP is an integer. Under this definition both 0 and 1 are
  2040. considered to be perfect squares.
  2041. 
  2042. File: gmp.info, Node: Number Theoretic Functions, Next: Integer Comparisons, Prev: Integer Roots, Up: Integer Functions
  2043. 5.9 Number Theoretic Functions
  2044. ==============================
  2045. -- Function: int mpz_probab_prime_p (const mpz_t N, int REPS)
  2046. Determine whether N is prime. Return 2 if N is definitely prime,
  2047. return 1 if N is probably prime (without being certain), or return
  2048. 0 if N is definitely non-prime.
  2049. This function performs some trial divisions, then REPS Miller-Rabin
  2050. probabilistic primality tests. A higher REPS value will reduce the
  2051. chances of a non-prime being identified as "probably prime". A
  2052. composite number will be identified as a prime with a probability
  2053. of less than 4^(-REPS). Reasonable values of REPS are between 15
  2054. and 50.
  2055. -- Function: void mpz_nextprime (mpz_t ROP, const mpz_t OP)
  2056. Set ROP to the next prime greater than OP.
  2057. This function uses a probabilistic algorithm to identify primes.
  2058. For practical purposes it's adequate, the chance of a composite
  2059. passing will be extremely small.
  2060. -- Function: void mpz_gcd (mpz_t ROP, const mpz_t OP1, const mpz_t OP2)
  2061. Set ROP to the greatest common divisor of OP1 and OP2. The result
  2062. is always positive even if one or both input operands are negative.
  2063. Except if both inputs are zero; then this function defines gcd(0,0)
  2064. = 0.
  2065. -- Function: unsigned long int mpz_gcd_ui (mpz_t ROP, const mpz_t OP1,
  2066. unsigned long int OP2)
  2067. Compute the greatest common divisor of OP1 and OP2. If ROP is not
  2068. 'NULL', store the result there.
  2069. If the result is small enough to fit in an 'unsigned long int', it
  2070. is returned. If the result does not fit, 0 is returned, and the
  2071. result is equal to the argument OP1. Note that the result will
  2072. always fit if OP2 is non-zero.
  2073. -- Function: void mpz_gcdext (mpz_t G, mpz_t S, mpz_t T, const mpz_t A,
  2074. const mpz_t B)
  2075. Set G to the greatest common divisor of A and B, and in addition
  2076. set S and T to coefficients satisfying A*S + B*T = G. The value in
  2077. G is always positive, even if one or both of A and B are negative
  2078. (or zero if both inputs are zero). The values in S and T are
  2079. chosen such that normally, abs(S) < abs(B) / (2 G) and abs(T) <
  2080. abs(A) / (2 G), and these relations define S and T uniquely. There
  2081. are a few exceptional cases:
  2082. If abs(A) = abs(B), then S = 0, T = sgn(B).
  2083. Otherwise, S = sgn(A) if B = 0 or abs(B) = 2 G, and T = sgn(B) if A
  2084. = 0 or abs(A) = 2 G.
  2085. In all cases, S = 0 if and only if G = abs(B), i.e., if B divides A
  2086. or A = B = 0.
  2087. If T is 'NULL' then that value is not computed.
  2088. -- Function: void mpz_lcm (mpz_t ROP, const mpz_t OP1, const mpz_t OP2)
  2089. -- Function: void mpz_lcm_ui (mpz_t ROP, const mpz_t OP1, unsigned long
  2090. OP2)
  2091. Set ROP to the least common multiple of OP1 and OP2. ROP is always
  2092. positive, irrespective of the signs of OP1 and OP2. ROP will be
  2093. zero if either OP1 or OP2 is zero.
  2094. -- Function: int mpz_invert (mpz_t ROP, const mpz_t OP1, const mpz_t
  2095. OP2)
  2096. Compute the inverse of OP1 modulo OP2 and put the result in ROP.
  2097. If the inverse exists, the return value is non-zero and ROP will
  2098. satisfy 0 <= ROP < abs(OP2) (with ROP = 0 possible only when
  2099. abs(OP2) = 1, i.e., in the somewhat degenerate zero ring). If an
  2100. inverse doesn't exist the return value is zero and ROP is
  2101. undefined. The behaviour of this function is undefined when OP2 is
  2102. zero.
  2103. -- Function: int mpz_jacobi (const mpz_t A, const mpz_t B)
  2104. Calculate the Jacobi symbol (A/B). This is defined only for B odd.
  2105. -- Function: int mpz_legendre (const mpz_t A, const mpz_t P)
  2106. Calculate the Legendre symbol (A/P). This is defined only for P an
  2107. odd positive prime, and for such P it's identical to the Jacobi
  2108. symbol.
  2109. -- Function: int mpz_kronecker (const mpz_t A, const mpz_t B)
  2110. -- Function: int mpz_kronecker_si (const mpz_t A, long B)
  2111. -- Function: int mpz_kronecker_ui (const mpz_t A, unsigned long B)
  2112. -- Function: int mpz_si_kronecker (long A, const mpz_t B)
  2113. -- Function: int mpz_ui_kronecker (unsigned long A, const mpz_t B)
  2114. Calculate the Jacobi symbol (A/B) with the Kronecker extension
  2115. (a/2)=(2/a) when a odd, or (a/2)=0 when a even.
  2116. When B is odd the Jacobi symbol and Kronecker symbol are identical,
  2117. so 'mpz_kronecker_ui' etc can be used for mixed precision Jacobi
  2118. symbols too.
  2119. For more information see Henri Cohen section 1.4.2 (*note
  2120. References::), or any number theory textbook. See also the example
  2121. program 'demos/qcn.c' which uses 'mpz_kronecker_ui'.
  2122. -- Function: mp_bitcnt_t mpz_remove (mpz_t ROP, const mpz_t OP, const
  2123. mpz_t F)
  2124. Remove all occurrences of the factor F from OP and store the result
  2125. in ROP. The return value is how many such occurrences were
  2126. removed.
  2127. -- Function: void mpz_fac_ui (mpz_t ROP, unsigned long int N)
  2128. -- Function: void mpz_2fac_ui (mpz_t ROP, unsigned long int N)
  2129. -- Function: void mpz_mfac_uiui (mpz_t ROP, unsigned long int N,
  2130. unsigned long int M)
  2131. Set ROP to the factorial of N: 'mpz_fac_ui' computes the plain
  2132. factorial N!, 'mpz_2fac_ui' computes the double-factorial N!!, and
  2133. 'mpz_mfac_uiui' the M-multi-factorial N!^(M).
  2134. -- Function: void mpz_primorial_ui (mpz_t ROP, unsigned long int N)
  2135. Set ROP to the primorial of N, i.e. the product of all positive
  2136. prime numbers <=N.
  2137. -- Function: void mpz_bin_ui (mpz_t ROP, const mpz_t N, unsigned long
  2138. int K)
  2139. -- Function: void mpz_bin_uiui (mpz_t ROP, unsigned long int N,
  2140. unsigned long int K)
  2141. Compute the binomial coefficient N over K and store the result in
  2142. ROP. Negative values of N are supported by 'mpz_bin_ui', using the
  2143. identity bin(-n,k) = (-1)^k * bin(n+k-1,k), see Knuth volume 1
  2144. section 1.2.6 part G.
  2145. -- Function: void mpz_fib_ui (mpz_t FN, unsigned long int N)
  2146. -- Function: void mpz_fib2_ui (mpz_t FN, mpz_t FNSUB1, unsigned long
  2147. int N)
  2148. 'mpz_fib_ui' sets FN to to F[n], the N'th Fibonacci number.
  2149. 'mpz_fib2_ui' sets FN to F[n], and FNSUB1 to F[n-1].
  2150. These functions are designed for calculating isolated Fibonacci
  2151. numbers. When a sequence of values is wanted it's best to start
  2152. with 'mpz_fib2_ui' and iterate the defining F[n+1]=F[n]+F[n-1] or
  2153. similar.
  2154. -- Function: void mpz_lucnum_ui (mpz_t LN, unsigned long int N)
  2155. -- Function: void mpz_lucnum2_ui (mpz_t LN, mpz_t LNSUB1, unsigned long
  2156. int N)
  2157. 'mpz_lucnum_ui' sets LN to to L[n], the N'th Lucas number.
  2158. 'mpz_lucnum2_ui' sets LN to L[n], and LNSUB1 to L[n-1].
  2159. These functions are designed for calculating isolated Lucas
  2160. numbers. When a sequence of values is wanted it's best to start
  2161. with 'mpz_lucnum2_ui' and iterate the defining L[n+1]=L[n]+L[n-1]
  2162. or similar.
  2163. The Fibonacci numbers and Lucas numbers are related sequences, so
  2164. it's never necessary to call both 'mpz_fib2_ui' and
  2165. 'mpz_lucnum2_ui'. The formulas for going from Fibonacci to Lucas
  2166. can be found in *note Lucas Numbers Algorithm::, the reverse is
  2167. straightforward too.
  2168. 
  2169. File: gmp.info, Node: Integer Comparisons, Next: Integer Logic and Bit Fiddling, Prev: Number Theoretic Functions, Up: Integer Functions
  2170. 5.10 Comparison Functions
  2171. =========================
  2172. -- Function: int mpz_cmp (const mpz_t OP1, const mpz_t OP2)
  2173. -- Function: int mpz_cmp_d (const mpz_t OP1, double OP2)
  2174. -- Macro: int mpz_cmp_si (const mpz_t OP1, signed long int OP2)
  2175. -- Macro: int mpz_cmp_ui (const mpz_t OP1, unsigned long int OP2)
  2176. Compare OP1 and OP2. Return a positive value if OP1 > OP2, zero if
  2177. OP1 = OP2, or a negative value if OP1 < OP2.
  2178. 'mpz_cmp_ui' and 'mpz_cmp_si' are macros and will evaluate their
  2179. arguments more than once. 'mpz_cmp_d' can be called with an
  2180. infinity, but results are undefined for a NaN.
  2181. -- Function: int mpz_cmpabs (const mpz_t OP1, const mpz_t OP2)
  2182. -- Function: int mpz_cmpabs_d (const mpz_t OP1, double OP2)
  2183. -- Function: int mpz_cmpabs_ui (const mpz_t OP1, unsigned long int OP2)
  2184. Compare the absolute values of OP1 and OP2. Return a positive
  2185. value if abs(OP1) > abs(OP2), zero if abs(OP1) = abs(OP2), or a
  2186. negative value if abs(OP1) < abs(OP2).
  2187. 'mpz_cmpabs_d' can be called with an infinity, but results are
  2188. undefined for a NaN.
  2189. -- Macro: int mpz_sgn (const mpz_t OP)
  2190. Return +1 if OP > 0, 0 if OP = 0, and -1 if OP < 0.
  2191. This function is actually implemented as a macro. It evaluates its
  2192. argument multiple times.
  2193. 
  2194. File: gmp.info, Node: Integer Logic and Bit Fiddling, Next: I/O of Integers, Prev: Integer Comparisons, Up: Integer Functions
  2195. 5.11 Logical and Bit Manipulation Functions
  2196. ===========================================
  2197. These functions behave as if twos complement arithmetic were used
  2198. (although sign-magnitude is the actual implementation). The least
  2199. significant bit is number 0.
  2200. -- Function: void mpz_and (mpz_t ROP, const mpz_t OP1, const mpz_t OP2)
  2201. Set ROP to OP1 bitwise-and OP2.
  2202. -- Function: void mpz_ior (mpz_t ROP, const mpz_t OP1, const mpz_t OP2)
  2203. Set ROP to OP1 bitwise inclusive-or OP2.
  2204. -- Function: void mpz_xor (mpz_t ROP, const mpz_t OP1, const mpz_t OP2)
  2205. Set ROP to OP1 bitwise exclusive-or OP2.
  2206. -- Function: void mpz_com (mpz_t ROP, const mpz_t OP)
  2207. Set ROP to the one's complement of OP.
  2208. -- Function: mp_bitcnt_t mpz_popcount (const mpz_t OP)
  2209. If OP>=0, return the population count of OP, which is the number of
  2210. 1 bits in the binary representation. If OP<0, the number of 1s is
  2211. infinite, and the return value is the largest possible
  2212. 'mp_bitcnt_t'.
  2213. -- Function: mp_bitcnt_t mpz_hamdist (const mpz_t OP1, const mpz_t OP2)
  2214. If OP1 and OP2 are both >=0 or both <0, return the hamming distance
  2215. between the two operands, which is the number of bit positions
  2216. where OP1 and OP2 have different bit values. If one operand is >=0
  2217. and the other <0 then the number of bits different is infinite, and
  2218. the return value is the largest possible 'mp_bitcnt_t'.
  2219. -- Function: mp_bitcnt_t mpz_scan0 (const mpz_t OP, mp_bitcnt_t
  2220. STARTING_BIT)
  2221. -- Function: mp_bitcnt_t mpz_scan1 (const mpz_t OP, mp_bitcnt_t
  2222. STARTING_BIT)
  2223. Scan OP, starting from bit STARTING_BIT, towards more significant
  2224. bits, until the first 0 or 1 bit (respectively) is found. Return
  2225. the index of the found bit.
  2226. If the bit at STARTING_BIT is already what's sought, then
  2227. STARTING_BIT is returned.
  2228. If there's no bit found, then the largest possible 'mp_bitcnt_t' is
  2229. returned. This will happen in 'mpz_scan0' past the end of a
  2230. negative number, or 'mpz_scan1' past the end of a nonnegative
  2231. number.
  2232. -- Function: void mpz_setbit (mpz_t ROP, mp_bitcnt_t BIT_INDEX)
  2233. Set bit BIT_INDEX in ROP.
  2234. -- Function: void mpz_clrbit (mpz_t ROP, mp_bitcnt_t BIT_INDEX)
  2235. Clear bit BIT_INDEX in ROP.
  2236. -- Function: void mpz_combit (mpz_t ROP, mp_bitcnt_t BIT_INDEX)
  2237. Complement bit BIT_INDEX in ROP.
  2238. -- Function: int mpz_tstbit (const mpz_t OP, mp_bitcnt_t BIT_INDEX)
  2239. Test bit BIT_INDEX in OP and return 0 or 1 accordingly.
  2240. 
  2241. File: gmp.info, Node: I/O of Integers, Next: Integer Random Numbers, Prev: Integer Logic and Bit Fiddling, Up: Integer Functions
  2242. 5.12 Input and Output Functions
  2243. ===============================
  2244. Functions that perform input from a stdio stream, and functions that
  2245. output to a stdio stream, of 'mpz' numbers. Passing a 'NULL' pointer
  2246. for a STREAM argument to any of these functions will make them read from
  2247. 'stdin' and write to 'stdout', respectively.
  2248. When using any of these functions, it is a good idea to include
  2249. 'stdio.h' before 'gmp.h', since that will allow 'gmp.h' to define
  2250. prototypes for these functions.
  2251. See also *note Formatted Output:: and *note Formatted Input::.
  2252. -- Function: size_t mpz_out_str (FILE *STREAM, int BASE, const mpz_t
  2253. OP)
  2254. Output OP on stdio stream STREAM, as a string of digits in base
  2255. BASE. The base argument may vary from 2 to 62 or from -2 to -36.
  2256. For BASE in the range 2..36, digits and lower-case letters are
  2257. used; for -2..-36, digits and upper-case letters are used; for
  2258. 37..62, digits, upper-case letters, and lower-case letters (in that
  2259. significance order) are used.
  2260. Return the number of bytes written, or if an error occurred, return
  2261. 0.
  2262. -- Function: size_t mpz_inp_str (mpz_t ROP, FILE *STREAM, int BASE)
  2263. Input a possibly white-space preceded string in base BASE from
  2264. stdio stream STREAM, and put the read integer in ROP.
  2265. The BASE may vary from 2 to 62, or if BASE is 0, then the leading
  2266. characters are used: '0x' and '0X' for hexadecimal, '0b' and '0B'
  2267. for binary, '0' for octal, or decimal otherwise.
  2268. For bases up to 36, case is ignored; upper-case and lower-case
  2269. letters have the same value. For bases 37 to 62, upper-case letter
  2270. represent the usual 10..35 while lower-case letter represent
  2271. 36..61.
  2272. Return the number of bytes read, or if an error occurred, return 0.
  2273. -- Function: size_t mpz_out_raw (FILE *STREAM, const mpz_t OP)
  2274. Output OP on stdio stream STREAM, in raw binary format. The
  2275. integer is written in a portable format, with 4 bytes of size
  2276. information, and that many bytes of limbs. Both the size and the
  2277. limbs are written in decreasing significance order (i.e., in
  2278. big-endian).
  2279. The output can be read with 'mpz_inp_raw'.
  2280. Return the number of bytes written, or if an error occurred, return
  2281. 0.
  2282. The output of this can not be read by 'mpz_inp_raw' from GMP 1,
  2283. because of changes necessary for compatibility between 32-bit and
  2284. 64-bit machines.
  2285. -- Function: size_t mpz_inp_raw (mpz_t ROP, FILE *STREAM)
  2286. Input from stdio stream STREAM in the format written by
  2287. 'mpz_out_raw', and put the result in ROP. Return the number of
  2288. bytes read, or if an error occurred, return 0.
  2289. This routine can read the output from 'mpz_out_raw' also from GMP
  2290. 1, in spite of changes necessary for compatibility between 32-bit
  2291. and 64-bit machines.
  2292. 
  2293. File: gmp.info, Node: Integer Random Numbers, Next: Integer Import and Export, Prev: I/O of Integers, Up: Integer Functions
  2294. 5.13 Random Number Functions
  2295. ============================
  2296. The random number functions of GMP come in two groups; older function
  2297. that rely on a global state, and newer functions that accept a state
  2298. parameter that is read and modified. Please see the *note Random Number
  2299. Functions:: for more information on how to use and not to use random
  2300. number functions.
  2301. -- Function: void mpz_urandomb (mpz_t ROP, gmp_randstate_t STATE,
  2302. mp_bitcnt_t N)
  2303. Generate a uniformly distributed random integer in the range 0 to
  2304. 2^N-1, inclusive.
  2305. The variable STATE must be initialized by calling one of the
  2306. 'gmp_randinit' functions (*note Random State Initialization::)
  2307. before invoking this function.
  2308. -- Function: void mpz_urandomm (mpz_t ROP, gmp_randstate_t STATE, const
  2309. mpz_t N)
  2310. Generate a uniform random integer in the range 0 to N-1, inclusive.
  2311. The variable STATE must be initialized by calling one of the
  2312. 'gmp_randinit' functions (*note Random State Initialization::)
  2313. before invoking this function.
  2314. -- Function: void mpz_rrandomb (mpz_t ROP, gmp_randstate_t STATE,
  2315. mp_bitcnt_t N)
  2316. Generate a random integer with long strings of zeros and ones in
  2317. the binary representation. Useful for testing functions and
  2318. algorithms, since this kind of random numbers have proven to be
  2319. more likely to trigger corner-case bugs. The random number will be
  2320. in the range 2^N-1 to 2^N-1, inclusive.
  2321. The variable STATE must be initialized by calling one of the
  2322. 'gmp_randinit' functions (*note Random State Initialization::)
  2323. before invoking this function.
  2324. -- Function: void mpz_random (mpz_t ROP, mp_size_t MAX_SIZE)
  2325. Generate a random integer of at most MAX_SIZE limbs. The generated
  2326. random number doesn't satisfy any particular requirements of
  2327. randomness. Negative random numbers are generated when MAX_SIZE is
  2328. negative.
  2329. This function is obsolete. Use 'mpz_urandomb' or 'mpz_urandomm'
  2330. instead.
  2331. -- Function: void mpz_random2 (mpz_t ROP, mp_size_t MAX_SIZE)
  2332. Generate a random integer of at most MAX_SIZE limbs, with long
  2333. strings of zeros and ones in the binary representation. Useful for
  2334. testing functions and algorithms, since this kind of random numbers
  2335. have proven to be more likely to trigger corner-case bugs.
  2336. Negative random numbers are generated when MAX_SIZE is negative.
  2337. This function is obsolete. Use 'mpz_rrandomb' instead.
  2338. 
  2339. File: gmp.info, Node: Integer Import and Export, Next: Miscellaneous Integer Functions, Prev: Integer Random Numbers, Up: Integer Functions
  2340. 5.14 Integer Import and Export
  2341. ==============================
  2342. 'mpz_t' variables can be converted to and from arbitrary words of binary
  2343. data with the following functions.
  2344. -- Function: void mpz_import (mpz_t ROP, size_t COUNT, int ORDER,
  2345. size_t SIZE, int ENDIAN, size_t NAILS, const void *OP)
  2346. Set ROP from an array of word data at OP.
  2347. The parameters specify the format of the data. COUNT many words
  2348. are read, each SIZE bytes. ORDER can be 1 for most significant
  2349. word first or -1 for least significant first. Within each word
  2350. ENDIAN can be 1 for most significant byte first, -1 for least
  2351. significant first, or 0 for the native endianness of the host CPU.
  2352. The most significant NAILS bits of each word are skipped, this can
  2353. be 0 to use the full words.
  2354. There is no sign taken from the data, ROP will simply be a positive
  2355. integer. An application can handle any sign itself, and apply it
  2356. for instance with 'mpz_neg'.
  2357. There are no data alignment restrictions on OP, any address is
  2358. allowed.
  2359. Here's an example converting an array of 'unsigned long' data, most
  2360. significant element first, and host byte order within each value.
  2361. unsigned long a[20];
  2362. /* Initialize Z and A */
  2363. mpz_import (z, 20, 1, sizeof(a[0]), 0, 0, a);
  2364. This example assumes the full 'sizeof' bytes are used for data in
  2365. the given type, which is usually true, and certainly true for
  2366. 'unsigned long' everywhere we know of. However on Cray vector
  2367. systems it may be noted that 'short' and 'int' are always stored in
  2368. 8 bytes (and with 'sizeof' indicating that) but use only 32 or 46
  2369. bits. The NAILS feature can account for this, by passing for
  2370. instance '8*sizeof(int)-INT_BIT'.
  2371. -- Function: void * mpz_export (void *ROP, size_t *COUNTP, int ORDER,
  2372. size_t SIZE, int ENDIAN, size_t NAILS, const mpz_t OP)
  2373. Fill ROP with word data from OP.
  2374. The parameters specify the format of the data produced. Each word
  2375. will be SIZE bytes and ORDER can be 1 for most significant word
  2376. first or -1 for least significant first. Within each word ENDIAN
  2377. can be 1 for most significant byte first, -1 for least significant
  2378. first, or 0 for the native endianness of the host CPU. The most
  2379. significant NAILS bits of each word are unused and set to zero,
  2380. this can be 0 to produce full words.
  2381. The number of words produced is written to '*COUNTP', or COUNTP can
  2382. be 'NULL' to discard the count. ROP must have enough space for the
  2383. data, or if ROP is 'NULL' then a result array of the necessary size
  2384. is allocated using the current GMP allocation function (*note
  2385. Custom Allocation::). In either case the return value is the
  2386. destination used, either ROP or the allocated block.
  2387. If OP is non-zero then the most significant word produced will be
  2388. non-zero. If OP is zero then the count returned will be zero and
  2389. nothing written to ROP. If ROP is 'NULL' in this case, no block is
  2390. allocated, just 'NULL' is returned.
  2391. The sign of OP is ignored, just the absolute value is exported. An
  2392. application can use 'mpz_sgn' to get the sign and handle it as
  2393. desired. (*note Integer Comparisons::)
  2394. There are no data alignment restrictions on ROP, any address is
  2395. allowed.
  2396. When an application is allocating space itself the required size
  2397. can be determined with a calculation like the following. Since
  2398. 'mpz_sizeinbase' always returns at least 1, 'count' here will be at
  2399. least one, which avoids any portability problems with 'malloc(0)',
  2400. though if 'z' is zero no space at all is actually needed (or
  2401. written).
  2402. numb = 8*size - nail;
  2403. count = (mpz_sizeinbase (z, 2) + numb-1) / numb;
  2404. p = malloc (count * size);
  2405. 
  2406. File: gmp.info, Node: Miscellaneous Integer Functions, Next: Integer Special Functions, Prev: Integer Import and Export, Up: Integer Functions
  2407. 5.15 Miscellaneous Functions
  2408. ============================
  2409. -- Function: int mpz_fits_ulong_p (const mpz_t OP)
  2410. -- Function: int mpz_fits_slong_p (const mpz_t OP)
  2411. -- Function: int mpz_fits_uint_p (const mpz_t OP)
  2412. -- Function: int mpz_fits_sint_p (const mpz_t OP)
  2413. -- Function: int mpz_fits_ushort_p (const mpz_t OP)
  2414. -- Function: int mpz_fits_sshort_p (const mpz_t OP)
  2415. Return non-zero iff the value of OP fits in an 'unsigned long int',
  2416. 'signed long int', 'unsigned int', 'signed int', 'unsigned short
  2417. int', or 'signed short int', respectively. Otherwise, return zero.
  2418. -- Macro: int mpz_odd_p (const mpz_t OP)
  2419. -- Macro: int mpz_even_p (const mpz_t OP)
  2420. Determine whether OP is odd or even, respectively. Return non-zero
  2421. if yes, zero if no. These macros evaluate their argument more than
  2422. once.
  2423. -- Function: size_t mpz_sizeinbase (const mpz_t OP, int BASE)
  2424. Return the size of OP measured in number of digits in the given
  2425. BASE. BASE can vary from 2 to 62. The sign of OP is ignored, just
  2426. the absolute value is used. The result will be either exact or 1
  2427. too big. If BASE is a power of 2, the result is always exact. If
  2428. OP is zero the return value is always 1.
  2429. This function can be used to determine the space required when
  2430. converting OP to a string. The right amount of allocation is
  2431. normally two more than the value returned by 'mpz_sizeinbase', one
  2432. extra for a minus sign and one for the null-terminator.
  2433. It will be noted that 'mpz_sizeinbase(OP,2)' can be used to locate
  2434. the most significant 1 bit in OP, counting from 1. (Unlike the
  2435. bitwise functions which start from 0, *Note Logical and Bit
  2436. Manipulation Functions: Integer Logic and Bit Fiddling.)
  2437. 
  2438. File: gmp.info, Node: Integer Special Functions, Prev: Miscellaneous Integer Functions, Up: Integer Functions
  2439. 5.16 Special Functions
  2440. ======================
  2441. The functions in this section are for various special purposes. Most
  2442. applications will not need them.
  2443. -- Function: void mpz_array_init (mpz_t INTEGER_ARRAY, mp_size_t
  2444. ARRAY_SIZE, mp_size_t FIXED_NUM_BITS)
  2445. *This is an obsolete function. Do not use it.*
  2446. -- Function: void * _mpz_realloc (mpz_t INTEGER, mp_size_t NEW_ALLOC)
  2447. Change the space for INTEGER to NEW_ALLOC limbs. The value in
  2448. INTEGER is preserved if it fits, or is set to 0 if not. The return
  2449. value is not useful to applications and should be ignored.
  2450. 'mpz_realloc2' is the preferred way to accomplish allocation
  2451. changes like this. 'mpz_realloc2' and '_mpz_realloc' are the same
  2452. except that '_mpz_realloc' takes its size in limbs.
  2453. -- Function: mp_limb_t mpz_getlimbn (const mpz_t OP, mp_size_t N)
  2454. Return limb number N from OP. The sign of OP is ignored, just the
  2455. absolute value is used. The least significant limb is number 0.
  2456. 'mpz_size' can be used to find how many limbs make up OP.
  2457. 'mpz_getlimbn' returns zero if N is outside the range 0 to
  2458. 'mpz_size(OP)-1'.
  2459. -- Function: size_t mpz_size (const mpz_t OP)
  2460. Return the size of OP measured in number of limbs. If OP is zero,
  2461. the returned value will be zero.
  2462. -- Function: const mp_limb_t * mpz_limbs_read (const mpz_t X)
  2463. Return a pointer to the limb array representing the absolute value
  2464. of X. The size of the array is 'mpz_size(X)'. Intended for read
  2465. access only.
  2466. -- Function: mp_limb_t * mpz_limbs_write (mpz_t X, mp_size_t N)
  2467. -- Function: mp_limb_t * mpz_limbs_modify (mpz_t X, mp_size_t N)
  2468. Return a pointer to the limb array, intended for write access. The
  2469. array is reallocated as needed, to make room for N limbs. Requires
  2470. N > 0. The 'mpz_limbs_modify' function returns an array that holds
  2471. the old absolute value of X, while 'mpz_limbs_write' may destroy
  2472. the old value and return an array with unspecified contents.
  2473. -- Function: void mpz_limbs_finish (mpz_t X, mp_size_t S)
  2474. Updates the internal size field of X. Used after writing to the
  2475. limb array pointer returned by 'mpz_limbs_write' or
  2476. 'mpz_limbs_modify' is completed. The array should contain abs(S)
  2477. valid limbs, representing the new absolute value for X, and the
  2478. sign of X is taken from the sign of S. This function never
  2479. reallocates X, so the limb pointer remains valid.
  2480. void foo (mpz_t x)
  2481. {
  2482. mp_size_t n, i;
  2483. mp_limb_t *xp;
  2484. n = mpz_size (x);
  2485. xp = mpz_limbs_modify (x, 2*n);
  2486. for (i = 0; i < n; i++)
  2487. xp[n+i] = xp[n-1-i];
  2488. mpz_limbs_finish (x, mpz_sgn (x) < 0 ? - 2*n : 2*n);
  2489. }
  2490. -- Function: mpz_srcptr mpz_roinit_n (mpz_t X, const mp_limb_t *XP,
  2491. mp_size_t XS)
  2492. Special initialization of X, using the given limb array and size.
  2493. X should be treated as read-only: it can be passed safely as input
  2494. to any mpz function, but not as an output. The array XP must point
  2495. to at least a readable limb, its size is abs(XS), and the sign of X
  2496. is the sign of XS. For convenience, the function returns X, but
  2497. cast to a const pointer type.
  2498. void foo (mpz_t x)
  2499. {
  2500. static const mp_limb_t y[3] = { 0x1, 0x2, 0x3 };
  2501. mpz_t tmp;
  2502. mpz_add (x, x, mpz_roinit_n (tmp, y, 3));
  2503. }
  2504. -- Macro: mpz_t MPZ_ROINIT_N (mp_limb_t *XP, mp_size_t XS)
  2505. This macro expands to an initializer which can be assigned to an
  2506. mpz_t variable. The limb array XP must point to at least a
  2507. readable limb, moreover, unlike the 'mpz_roinit_n' function, the
  2508. array must be normalized: if XS is non-zero, then 'XP[abs(XS)-1]'
  2509. must be non-zero. Intended primarily for constant values. Using
  2510. it for non-constant values requires a C compiler supporting C99.
  2511. void foo (mpz_t x)
  2512. {
  2513. static const mp_limb_t ya[3] = { 0x1, 0x2, 0x3 };
  2514. static const mpz_t y = MPZ_ROINIT_N ((mp_limb_t *) ya, 3);
  2515. mpz_add (x, x, y);
  2516. }
  2517. 
  2518. File: gmp.info, Node: Rational Number Functions, Next: Floating-point Functions, Prev: Integer Functions, Up: Top
  2519. 6 Rational Number Functions
  2520. ***************************
  2521. This chapter describes the GMP functions for performing arithmetic on
  2522. rational numbers. These functions start with the prefix 'mpq_'.
  2523. Rational numbers are stored in objects of type 'mpq_t'.
  2524. All rational arithmetic functions assume operands have a canonical
  2525. form, and canonicalize their result. The canonical form means that the
  2526. denominator and the numerator have no common factors, and that the
  2527. denominator is positive. Zero has the unique representation 0/1.
  2528. Pure assignment functions do not canonicalize the assigned variable.
  2529. It is the responsibility of the user to canonicalize the assigned
  2530. variable before any arithmetic operations are performed on that
  2531. variable.
  2532. -- Function: void mpq_canonicalize (mpq_t OP)
  2533. Remove any factors that are common to the numerator and denominator
  2534. of OP, and make the denominator positive.
  2535. * Menu:
  2536. * Initializing Rationals::
  2537. * Rational Conversions::
  2538. * Rational Arithmetic::
  2539. * Comparing Rationals::
  2540. * Applying Integer Functions::
  2541. * I/O of Rationals::
  2542. 
  2543. File: gmp.info, Node: Initializing Rationals, Next: Rational Conversions, Prev: Rational Number Functions, Up: Rational Number Functions
  2544. 6.1 Initialization and Assignment Functions
  2545. ===========================================
  2546. -- Function: void mpq_init (mpq_t X)
  2547. Initialize X and set it to 0/1. Each variable should normally only
  2548. be initialized once, or at least cleared out (using the function
  2549. 'mpq_clear') between each initialization.
  2550. -- Function: void mpq_inits (mpq_t X, ...)
  2551. Initialize a NULL-terminated list of 'mpq_t' variables, and set
  2552. their values to 0/1.
  2553. -- Function: void mpq_clear (mpq_t X)
  2554. Free the space occupied by X. Make sure to call this function for
  2555. all 'mpq_t' variables when you are done with them.
  2556. -- Function: void mpq_clears (mpq_t X, ...)
  2557. Free the space occupied by a NULL-terminated list of 'mpq_t'
  2558. variables.
  2559. -- Function: void mpq_set (mpq_t ROP, const mpq_t OP)
  2560. -- Function: void mpq_set_z (mpq_t ROP, const mpz_t OP)
  2561. Assign ROP from OP.
  2562. -- Function: void mpq_set_ui (mpq_t ROP, unsigned long int OP1,
  2563. unsigned long int OP2)
  2564. -- Function: void mpq_set_si (mpq_t ROP, signed long int OP1, unsigned
  2565. long int OP2)
  2566. Set the value of ROP to OP1/OP2. Note that if OP1 and OP2 have
  2567. common factors, ROP has to be passed to 'mpq_canonicalize' before
  2568. any operations are performed on ROP.
  2569. -- Function: int mpq_set_str (mpq_t ROP, const char *STR, int BASE)
  2570. Set ROP from a null-terminated string STR in the given BASE.
  2571. The string can be an integer like "41" or a fraction like "41/152".
  2572. The fraction must be in canonical form (*note Rational Number
  2573. Functions::), or if not then 'mpq_canonicalize' must be called.
  2574. The numerator and optional denominator are parsed the same as in
  2575. 'mpz_set_str' (*note Assigning Integers::). White space is allowed
  2576. in the string, and is simply ignored. The BASE can vary from 2 to
  2577. 62, or if BASE is 0 then the leading characters are used: '0x' or
  2578. '0X' for hex, '0b' or '0B' for binary, '0' for octal, or decimal
  2579. otherwise. Note that this is done separately for the numerator and
  2580. denominator, so for instance '0xEF/100' is 239/100, whereas
  2581. '0xEF/0x100' is 239/256.
  2582. The return value is 0 if the entire string is a valid number, or -1
  2583. if not.
  2584. -- Function: void mpq_swap (mpq_t ROP1, mpq_t ROP2)
  2585. Swap the values ROP1 and ROP2 efficiently.
  2586. 
  2587. File: gmp.info, Node: Rational Conversions, Next: Rational Arithmetic, Prev: Initializing Rationals, Up: Rational Number Functions
  2588. 6.2 Conversion Functions
  2589. ========================
  2590. -- Function: double mpq_get_d (const mpq_t OP)
  2591. Convert OP to a 'double', truncating if necessary (i.e. rounding
  2592. towards zero).
  2593. If the exponent from the conversion is too big or too small to fit
  2594. a 'double' then the result is system dependent. For too big an
  2595. infinity is returned when available. For too small 0.0 is normally
  2596. returned. Hardware overflow, underflow and denorm traps may or may
  2597. not occur.
  2598. -- Function: void mpq_set_d (mpq_t ROP, double OP)
  2599. -- Function: void mpq_set_f (mpq_t ROP, const mpf_t OP)
  2600. Set ROP to the value of OP. There is no rounding, this conversion
  2601. is exact.
  2602. -- Function: char * mpq_get_str (char *STR, int BASE, const mpq_t OP)
  2603. Convert OP to a string of digits in base BASE. The base may vary
  2604. from 2 to 36. The string will be of the form 'num/den', or if the
  2605. denominator is 1 then just 'num'.
  2606. If STR is 'NULL', the result string is allocated using the current
  2607. allocation function (*note Custom Allocation::). The block will be
  2608. 'strlen(str)+1' bytes, that being exactly enough for the string and
  2609. null-terminator.
  2610. If STR is not 'NULL', it should point to a block of storage large
  2611. enough for the result, that being
  2612. mpz_sizeinbase (mpq_numref(OP), BASE)
  2613. + mpz_sizeinbase (mpq_denref(OP), BASE) + 3
  2614. The three extra bytes are for a possible minus sign, possible
  2615. slash, and the null-terminator.
  2616. A pointer to the result string is returned, being either the
  2617. allocated block, or the given STR.
  2618. 
  2619. File: gmp.info, Node: Rational Arithmetic, Next: Comparing Rationals, Prev: Rational Conversions, Up: Rational Number Functions
  2620. 6.3 Arithmetic Functions
  2621. ========================
  2622. -- Function: void mpq_add (mpq_t SUM, const mpq_t ADDEND1, const mpq_t
  2623. ADDEND2)
  2624. Set SUM to ADDEND1 + ADDEND2.
  2625. -- Function: void mpq_sub (mpq_t DIFFERENCE, const mpq_t MINUEND, const
  2626. mpq_t SUBTRAHEND)
  2627. Set DIFFERENCE to MINUEND - SUBTRAHEND.
  2628. -- Function: void mpq_mul (mpq_t PRODUCT, const mpq_t MULTIPLIER, const
  2629. mpq_t MULTIPLICAND)
  2630. Set PRODUCT to MULTIPLIER times MULTIPLICAND.
  2631. -- Function: void mpq_mul_2exp (mpq_t ROP, const mpq_t OP1, mp_bitcnt_t
  2632. OP2)
  2633. Set ROP to OP1 times 2 raised to OP2.
  2634. -- Function: void mpq_div (mpq_t QUOTIENT, const mpq_t DIVIDEND, const
  2635. mpq_t DIVISOR)
  2636. Set QUOTIENT to DIVIDEND/DIVISOR.
  2637. -- Function: void mpq_div_2exp (mpq_t ROP, const mpq_t OP1, mp_bitcnt_t
  2638. OP2)
  2639. Set ROP to OP1 divided by 2 raised to OP2.
  2640. -- Function: void mpq_neg (mpq_t NEGATED_OPERAND, const mpq_t OPERAND)
  2641. Set NEGATED_OPERAND to -OPERAND.
  2642. -- Function: void mpq_abs (mpq_t ROP, const mpq_t OP)
  2643. Set ROP to the absolute value of OP.
  2644. -- Function: void mpq_inv (mpq_t INVERTED_NUMBER, const mpq_t NUMBER)
  2645. Set INVERTED_NUMBER to 1/NUMBER. If the new denominator is zero,
  2646. this routine will divide by zero.
  2647. 
  2648. File: gmp.info, Node: Comparing Rationals, Next: Applying Integer Functions, Prev: Rational Arithmetic, Up: Rational Number Functions
  2649. 6.4 Comparison Functions
  2650. ========================
  2651. -- Function: int mpq_cmp (const mpq_t OP1, const mpq_t OP2)
  2652. -- Function: int mpq_cmp_z (const mpq_t OP1, const mpz_t OP2)
  2653. Compare OP1 and OP2. Return a positive value if OP1 > OP2, zero if
  2654. OP1 = OP2, and a negative value if OP1 < OP2.
  2655. To determine if two rationals are equal, 'mpq_equal' is faster than
  2656. 'mpq_cmp'.
  2657. -- Macro: int mpq_cmp_ui (const mpq_t OP1, unsigned long int NUM2,
  2658. unsigned long int DEN2)
  2659. -- Macro: int mpq_cmp_si (const mpq_t OP1, long int NUM2, unsigned long
  2660. int DEN2)
  2661. Compare OP1 and NUM2/DEN2. Return a positive value if OP1 >
  2662. NUM2/DEN2, zero if OP1 = NUM2/DEN2, and a negative value if OP1 <
  2663. NUM2/DEN2.
  2664. NUM2 and DEN2 are allowed to have common factors.
  2665. These functions are implemented as a macros and evaluate their
  2666. arguments multiple times.
  2667. -- Macro: int mpq_sgn (const mpq_t OP)
  2668. Return +1 if OP > 0, 0 if OP = 0, and -1 if OP < 0.
  2669. This function is actually implemented as a macro. It evaluates its
  2670. argument multiple times.
  2671. -- Function: int mpq_equal (const mpq_t OP1, const mpq_t OP2)
  2672. Return non-zero if OP1 and OP2 are equal, zero if they are
  2673. non-equal. Although 'mpq_cmp' can be used for the same purpose,
  2674. this function is much faster.
  2675. 
  2676. File: gmp.info, Node: Applying Integer Functions, Next: I/O of Rationals, Prev: Comparing Rationals, Up: Rational Number Functions
  2677. 6.5 Applying Integer Functions to Rationals
  2678. ===========================================
  2679. The set of 'mpq' functions is quite small. In particular, there are few
  2680. functions for either input or output. The following functions give
  2681. direct access to the numerator and denominator of an 'mpq_t'.
  2682. Note that if an assignment to the numerator and/or denominator could
  2683. take an 'mpq_t' out of the canonical form described at the start of this
  2684. chapter (*note Rational Number Functions::) then 'mpq_canonicalize' must
  2685. be called before any other 'mpq' functions are applied to that 'mpq_t'.
  2686. -- Macro: mpz_t mpq_numref (const mpq_t OP)
  2687. -- Macro: mpz_t mpq_denref (const mpq_t OP)
  2688. Return a reference to the numerator and denominator of OP,
  2689. respectively. The 'mpz' functions can be used on the result of
  2690. these macros.
  2691. -- Function: void mpq_get_num (mpz_t NUMERATOR, const mpq_t RATIONAL)
  2692. -- Function: void mpq_get_den (mpz_t DENOMINATOR, const mpq_t RATIONAL)
  2693. -- Function: void mpq_set_num (mpq_t RATIONAL, const mpz_t NUMERATOR)
  2694. -- Function: void mpq_set_den (mpq_t RATIONAL, const mpz_t DENOMINATOR)
  2695. Get or set the numerator or denominator of a rational. These
  2696. functions are equivalent to calling 'mpz_set' with an appropriate
  2697. 'mpq_numref' or 'mpq_denref'. Direct use of 'mpq_numref' or
  2698. 'mpq_denref' is recommended instead of these functions.
  2699. 
  2700. File: gmp.info, Node: I/O of Rationals, Prev: Applying Integer Functions, Up: Rational Number Functions
  2701. 6.6 Input and Output Functions
  2702. ==============================
  2703. Functions that perform input from a stdio stream, and functions that
  2704. output to a stdio stream, of 'mpq' numbers. Passing a 'NULL' pointer
  2705. for a STREAM argument to any of these functions will make them read from
  2706. 'stdin' and write to 'stdout', respectively.
  2707. When using any of these functions, it is a good idea to include
  2708. 'stdio.h' before 'gmp.h', since that will allow 'gmp.h' to define
  2709. prototypes for these functions.
  2710. See also *note Formatted Output:: and *note Formatted Input::.
  2711. -- Function: size_t mpq_out_str (FILE *STREAM, int BASE, const mpq_t
  2712. OP)
  2713. Output OP on stdio stream STREAM, as a string of digits in base
  2714. BASE. The base may vary from 2 to 36. Output is in the form
  2715. 'num/den' or if the denominator is 1 then just 'num'.
  2716. Return the number of bytes written, or if an error occurred, return
  2717. 0.
  2718. -- Function: size_t mpq_inp_str (mpq_t ROP, FILE *STREAM, int BASE)
  2719. Read a string of digits from STREAM and convert them to a rational
  2720. in ROP. Any initial white-space characters are read and discarded.
  2721. Return the number of characters read (including white space), or 0
  2722. if a rational could not be read.
  2723. The input can be a fraction like '17/63' or just an integer like
  2724. '123'. Reading stops at the first character not in this form, and
  2725. white space is not permitted within the string. If the input might
  2726. not be in canonical form, then 'mpq_canonicalize' must be called
  2727. (*note Rational Number Functions::).
  2728. The BASE can be between 2 and 36, or can be 0 in which case the
  2729. leading characters of the string determine the base, '0x' or '0X'
  2730. for hexadecimal, '0' for octal, or decimal otherwise. The leading
  2731. characters are examined separately for the numerator and
  2732. denominator of a fraction, so for instance '0x10/11' is 16/11,
  2733. whereas '0x10/0x11' is 16/17.
  2734. 
  2735. File: gmp.info, Node: Floating-point Functions, Next: Low-level Functions, Prev: Rational Number Functions, Up: Top
  2736. 7 Floating-point Functions
  2737. **************************
  2738. GMP floating point numbers are stored in objects of type 'mpf_t' and
  2739. functions operating on them have an 'mpf_' prefix.
  2740. The mantissa of each float has a user-selectable precision, in
  2741. practice only limited by available memory. Each variable has its own
  2742. precision, and that can be increased or decreased at any time. This
  2743. selectable precision is a minimum value, GMP rounds it up to a whole
  2744. limb.
  2745. The accuracy of a calculation is determined by the priorly set
  2746. precision of the destination variable and the numeric values of the
  2747. input variables. Input variables' set precisions do not affect
  2748. calculations (except indirectly as their values might have been affected
  2749. when they were assigned).
  2750. The exponent of each float has fixed precision, one machine word on
  2751. most systems. In the current implementation the exponent is a count of
  2752. limbs, so for example on a 32-bit system this means a range of roughly
  2753. 2^-68719476768 to 2^68719476736, or on a 64-bit system this will be much
  2754. greater. Note however that 'mpf_get_str' can only return an exponent
  2755. which fits an 'mp_exp_t' and currently 'mpf_set_str' doesn't accept
  2756. exponents bigger than a 'long'.
  2757. Each variable keeps track of the mantissa data actually in use. This
  2758. means that if a float is exactly represented in only a few bits then
  2759. only those bits will be used in a calculation, even if the variable's
  2760. selected precision is high. This is a performance optimization; it does
  2761. not affect the numeric results.
  2762. Internally, GMP sometimes calculates with higher precision than that
  2763. of the destination variable in order to limit errors. Final results are
  2764. always truncated to the destination variable's precision.
  2765. The mantissa is stored in binary. One consequence of this is that
  2766. decimal fractions like 0.1 cannot be represented exactly. The same is
  2767. true of plain IEEE 'double' floats. This makes both highly unsuitable
  2768. for calculations involving money or other values that should be exact
  2769. decimal fractions. (Suitably scaled integers, or perhaps rationals, are
  2770. better choices.)
  2771. The 'mpf' functions and variables have no special notion of infinity
  2772. or not-a-number, and applications must take care not to overflow the
  2773. exponent or results will be unpredictable.
  2774. Note that the 'mpf' functions are _not_ intended as a smooth
  2775. extension to IEEE P754 arithmetic. In particular results obtained on
  2776. one computer often differ from the results on a computer with a
  2777. different word size.
  2778. New projects should consider using the GMP extension library MPFR
  2779. (<http://mpfr.org>) instead. MPFR provides well-defined precision and
  2780. accurate rounding, and thereby naturally extends IEEE P754.
  2781. * Menu:
  2782. * Initializing Floats::
  2783. * Assigning Floats::
  2784. * Simultaneous Float Init & Assign::
  2785. * Converting Floats::
  2786. * Float Arithmetic::
  2787. * Float Comparison::
  2788. * I/O of Floats::
  2789. * Miscellaneous Float Functions::
  2790. 
  2791. File: gmp.info, Node: Initializing Floats, Next: Assigning Floats, Prev: Floating-point Functions, Up: Floating-point Functions
  2792. 7.1 Initialization Functions
  2793. ============================
  2794. -- Function: void mpf_set_default_prec (mp_bitcnt_t PREC)
  2795. Set the default precision to be *at least* PREC bits. All
  2796. subsequent calls to 'mpf_init' will use this precision, but
  2797. previously initialized variables are unaffected.
  2798. -- Function: mp_bitcnt_t mpf_get_default_prec (void)
  2799. Return the default precision actually used.
  2800. An 'mpf_t' object must be initialized before storing the first value
  2801. in it. The functions 'mpf_init' and 'mpf_init2' are used for that
  2802. purpose.
  2803. -- Function: void mpf_init (mpf_t X)
  2804. Initialize X to 0. Normally, a variable should be initialized once
  2805. only or at least be cleared, using 'mpf_clear', between
  2806. initializations. The precision of X is undefined unless a default
  2807. precision has already been established by a call to
  2808. 'mpf_set_default_prec'.
  2809. -- Function: void mpf_init2 (mpf_t X, mp_bitcnt_t PREC)
  2810. Initialize X to 0 and set its precision to be *at least* PREC bits.
  2811. Normally, a variable should be initialized once only or at least be
  2812. cleared, using 'mpf_clear', between initializations.
  2813. -- Function: void mpf_inits (mpf_t X, ...)
  2814. Initialize a NULL-terminated list of 'mpf_t' variables, and set
  2815. their values to 0. The precision of the initialized variables is
  2816. undefined unless a default precision has already been established
  2817. by a call to 'mpf_set_default_prec'.
  2818. -- Function: void mpf_clear (mpf_t X)
  2819. Free the space occupied by X. Make sure to call this function for
  2820. all 'mpf_t' variables when you are done with them.
  2821. -- Function: void mpf_clears (mpf_t X, ...)
  2822. Free the space occupied by a NULL-terminated list of 'mpf_t'
  2823. variables.
  2824. Here is an example on how to initialize floating-point variables:
  2825. {
  2826. mpf_t x, y;
  2827. mpf_init (x); /* use default precision */
  2828. mpf_init2 (y, 256); /* precision _at least_ 256 bits */
  2829. ...
  2830. /* Unless the program is about to exit, do ... */
  2831. mpf_clear (x);
  2832. mpf_clear (y);
  2833. }
  2834. The following three functions are useful for changing the precision
  2835. during a calculation. A typical use would be for adjusting the
  2836. precision gradually in iterative algorithms like Newton-Raphson, making
  2837. the computation precision closely match the actual accurate part of the
  2838. numbers.
  2839. -- Function: mp_bitcnt_t mpf_get_prec (const mpf_t OP)
  2840. Return the current precision of OP, in bits.
  2841. -- Function: void mpf_set_prec (mpf_t ROP, mp_bitcnt_t PREC)
  2842. Set the precision of ROP to be *at least* PREC bits. The value in
  2843. ROP will be truncated to the new precision.
  2844. This function requires a call to 'realloc', and so should not be
  2845. used in a tight loop.
  2846. -- Function: void mpf_set_prec_raw (mpf_t ROP, mp_bitcnt_t PREC)
  2847. Set the precision of ROP to be *at least* PREC bits, without
  2848. changing the memory allocated.
  2849. PREC must be no more than the allocated precision for ROP, that
  2850. being the precision when ROP was initialized, or in the most recent
  2851. 'mpf_set_prec'.
  2852. The value in ROP is unchanged, and in particular if it had a higher
  2853. precision than PREC it will retain that higher precision. New
  2854. values written to ROP will use the new PREC.
  2855. Before calling 'mpf_clear' or the full 'mpf_set_prec', another
  2856. 'mpf_set_prec_raw' call must be made to restore ROP to its original
  2857. allocated precision. Failing to do so will have unpredictable
  2858. results.
  2859. 'mpf_get_prec' can be used before 'mpf_set_prec_raw' to get the
  2860. original allocated precision. After 'mpf_set_prec_raw' it reflects
  2861. the PREC value set.
  2862. 'mpf_set_prec_raw' is an efficient way to use an 'mpf_t' variable
  2863. at different precisions during a calculation, perhaps to gradually
  2864. increase precision in an iteration, or just to use various
  2865. different precisions for different purposes during a calculation.
  2866. 
  2867. File: gmp.info, Node: Assigning Floats, Next: Simultaneous Float Init & Assign, Prev: Initializing Floats, Up: Floating-point Functions
  2868. 7.2 Assignment Functions
  2869. ========================
  2870. These functions assign new values to already initialized floats (*note
  2871. Initializing Floats::).
  2872. -- Function: void mpf_set (mpf_t ROP, const mpf_t OP)
  2873. -- Function: void mpf_set_ui (mpf_t ROP, unsigned long int OP)
  2874. -- Function: void mpf_set_si (mpf_t ROP, signed long int OP)
  2875. -- Function: void mpf_set_d (mpf_t ROP, double OP)
  2876. -- Function: void mpf_set_z (mpf_t ROP, const mpz_t OP)
  2877. -- Function: void mpf_set_q (mpf_t ROP, const mpq_t OP)
  2878. Set the value of ROP from OP.
  2879. -- Function: int mpf_set_str (mpf_t ROP, const char *STR, int BASE)
  2880. Set the value of ROP from the string in STR. The string is of the
  2881. form 'M@N' or, if the base is 10 or less, alternatively 'MeN'. 'M'
  2882. is the mantissa and 'N' is the exponent. The mantissa is always in
  2883. the specified base. The exponent is either in the specified base
  2884. or, if BASE is negative, in decimal. The decimal point expected is
  2885. taken from the current locale, on systems providing 'localeconv'.
  2886. The argument BASE may be in the ranges 2 to 62, or -62 to -2.
  2887. Negative values are used to specify that the exponent is in
  2888. decimal.
  2889. For bases up to 36, case is ignored; upper-case and lower-case
  2890. letters have the same value; for bases 37 to 62, upper-case letter
  2891. represent the usual 10..35 while lower-case letter represent
  2892. 36..61.
  2893. Unlike the corresponding 'mpz' function, the base will not be
  2894. determined from the leading characters of the string if BASE is 0.
  2895. This is so that numbers like '0.23' are not interpreted as octal.
  2896. White space is allowed in the string, and is simply ignored. [This
  2897. is not really true; white-space is ignored in the beginning of the
  2898. string and within the mantissa, but not in other places, such as
  2899. after a minus sign or in the exponent. We are considering changing
  2900. the definition of this function, making it fail when there is any
  2901. white-space in the input, since that makes a lot of sense. Please
  2902. tell us your opinion about this change. Do you really want it to
  2903. accept "3 14" as meaning 314 as it does now?]
  2904. This function returns 0 if the entire string is a valid number in
  2905. base BASE. Otherwise it returns -1.
  2906. -- Function: void mpf_swap (mpf_t ROP1, mpf_t ROP2)
  2907. Swap ROP1 and ROP2 efficiently. Both the values and the precisions
  2908. of the two variables are swapped.
  2909. 
  2910. File: gmp.info, Node: Simultaneous Float Init & Assign, Next: Converting Floats, Prev: Assigning Floats, Up: Floating-point Functions
  2911. 7.3 Combined Initialization and Assignment Functions
  2912. ====================================================
  2913. For convenience, GMP provides a parallel series of initialize-and-set
  2914. functions which initialize the output and then store the value there.
  2915. These functions' names have the form 'mpf_init_set...'
  2916. Once the float has been initialized by any of the 'mpf_init_set...'
  2917. functions, it can be used as the source or destination operand for the
  2918. ordinary float functions. Don't use an initialize-and-set function on a
  2919. variable already initialized!
  2920. -- Function: void mpf_init_set (mpf_t ROP, const mpf_t OP)
  2921. -- Function: void mpf_init_set_ui (mpf_t ROP, unsigned long int OP)
  2922. -- Function: void mpf_init_set_si (mpf_t ROP, signed long int OP)
  2923. -- Function: void mpf_init_set_d (mpf_t ROP, double OP)
  2924. Initialize ROP and set its value from OP.
  2925. The precision of ROP will be taken from the active default
  2926. precision, as set by 'mpf_set_default_prec'.
  2927. -- Function: int mpf_init_set_str (mpf_t ROP, const char *STR, int
  2928. BASE)
  2929. Initialize ROP and set its value from the string in STR. See
  2930. 'mpf_set_str' above for details on the assignment operation.
  2931. Note that ROP is initialized even if an error occurs. (I.e., you
  2932. have to call 'mpf_clear' for it.)
  2933. The precision of ROP will be taken from the active default
  2934. precision, as set by 'mpf_set_default_prec'.
  2935. 
  2936. File: gmp.info, Node: Converting Floats, Next: Float Arithmetic, Prev: Simultaneous Float Init & Assign, Up: Floating-point Functions
  2937. 7.4 Conversion Functions
  2938. ========================
  2939. -- Function: double mpf_get_d (const mpf_t OP)
  2940. Convert OP to a 'double', truncating if necessary (i.e. rounding
  2941. towards zero).
  2942. If the exponent in OP is too big or too small to fit a 'double'
  2943. then the result is system dependent. For too big an infinity is
  2944. returned when available. For too small 0.0 is normally returned.
  2945. Hardware overflow, underflow and denorm traps may or may not occur.
  2946. -- Function: double mpf_get_d_2exp (signed long int *EXP, const mpf_t
  2947. OP)
  2948. Convert OP to a 'double', truncating if necessary (i.e. rounding
  2949. towards zero), and with an exponent returned separately.
  2950. The return value is in the range 0.5<=abs(D)<1 and the exponent is
  2951. stored to '*EXP'. D * 2^EXP is the (truncated) OP value. If OP is
  2952. zero, the return is 0.0 and 0 is stored to '*EXP'.
  2953. This is similar to the standard C 'frexp' function (*note
  2954. (libc)Normalization Functions::).
  2955. -- Function: long mpf_get_si (const mpf_t OP)
  2956. -- Function: unsigned long mpf_get_ui (const mpf_t OP)
  2957. Convert OP to a 'long' or 'unsigned long', truncating any fraction
  2958. part. If OP is too big for the return type, the result is
  2959. undefined.
  2960. See also 'mpf_fits_slong_p' and 'mpf_fits_ulong_p' (*note
  2961. Miscellaneous Float Functions::).
  2962. -- Function: char * mpf_get_str (char *STR, mp_exp_t *EXPPTR, int BASE,
  2963. size_t N_DIGITS, const mpf_t OP)
  2964. Convert OP to a string of digits in base BASE. The base argument
  2965. may vary from 2 to 62 or from -2 to -36. Up to N_DIGITS digits
  2966. will be generated. Trailing zeros are not returned. No more
  2967. digits than can be accurately represented by OP are ever generated.
  2968. If N_DIGITS is 0 then that accurate maximum number of digits are
  2969. generated.
  2970. For BASE in the range 2..36, digits and lower-case letters are
  2971. used; for -2..-36, digits and upper-case letters are used; for
  2972. 37..62, digits, upper-case letters, and lower-case letters (in that
  2973. significance order) are used.
  2974. If STR is 'NULL', the result string is allocated using the current
  2975. allocation function (*note Custom Allocation::). The block will be
  2976. 'strlen(str)+1' bytes, that being exactly enough for the string and
  2977. null-terminator.
  2978. If STR is not 'NULL', it should point to a block of N_DIGITS + 2
  2979. bytes, that being enough for the mantissa, a possible minus sign,
  2980. and a null-terminator. When N_DIGITS is 0 to get all significant
  2981. digits, an application won't be able to know the space required,
  2982. and STR should be 'NULL' in that case.
  2983. The generated string is a fraction, with an implicit radix point
  2984. immediately to the left of the first digit. The applicable
  2985. exponent is written through the EXPPTR pointer. For example, the
  2986. number 3.1416 would be returned as string "31416" and exponent 1.
  2987. When OP is zero, an empty string is produced and the exponent
  2988. returned is 0.
  2989. A pointer to the result string is returned, being either the
  2990. allocated block or the given STR.
  2991. 
  2992. File: gmp.info, Node: Float Arithmetic, Next: Float Comparison, Prev: Converting Floats, Up: Floating-point Functions
  2993. 7.5 Arithmetic Functions
  2994. ========================
  2995. -- Function: void mpf_add (mpf_t ROP, const mpf_t OP1, const mpf_t OP2)
  2996. -- Function: void mpf_add_ui (mpf_t ROP, const mpf_t OP1, unsigned long
  2997. int OP2)
  2998. Set ROP to OP1 + OP2.
  2999. -- Function: void mpf_sub (mpf_t ROP, const mpf_t OP1, const mpf_t OP2)
  3000. -- Function: void mpf_ui_sub (mpf_t ROP, unsigned long int OP1, const
  3001. mpf_t OP2)
  3002. -- Function: void mpf_sub_ui (mpf_t ROP, const mpf_t OP1, unsigned long
  3003. int OP2)
  3004. Set ROP to OP1 - OP2.
  3005. -- Function: void mpf_mul (mpf_t ROP, const mpf_t OP1, const mpf_t OP2)
  3006. -- Function: void mpf_mul_ui (mpf_t ROP, const mpf_t OP1, unsigned long
  3007. int OP2)
  3008. Set ROP to OP1 times OP2.
  3009. Division is undefined if the divisor is zero, and passing a zero
  3010. divisor to the divide functions will make these functions intentionally
  3011. divide by zero. This lets the user handle arithmetic exceptions in
  3012. these functions in the same manner as other arithmetic exceptions.
  3013. -- Function: void mpf_div (mpf_t ROP, const mpf_t OP1, const mpf_t OP2)
  3014. -- Function: void mpf_ui_div (mpf_t ROP, unsigned long int OP1, const
  3015. mpf_t OP2)
  3016. -- Function: void mpf_div_ui (mpf_t ROP, const mpf_t OP1, unsigned long
  3017. int OP2)
  3018. Set ROP to OP1/OP2.
  3019. -- Function: void mpf_sqrt (mpf_t ROP, const mpf_t OP)
  3020. -- Function: void mpf_sqrt_ui (mpf_t ROP, unsigned long int OP)
  3021. Set ROP to the square root of OP.
  3022. -- Function: void mpf_pow_ui (mpf_t ROP, const mpf_t OP1, unsigned long
  3023. int OP2)
  3024. Set ROP to OP1 raised to the power OP2.
  3025. -- Function: void mpf_neg (mpf_t ROP, const mpf_t OP)
  3026. Set ROP to -OP.
  3027. -- Function: void mpf_abs (mpf_t ROP, const mpf_t OP)
  3028. Set ROP to the absolute value of OP.
  3029. -- Function: void mpf_mul_2exp (mpf_t ROP, const mpf_t OP1, mp_bitcnt_t
  3030. OP2)
  3031. Set ROP to OP1 times 2 raised to OP2.
  3032. -- Function: void mpf_div_2exp (mpf_t ROP, const mpf_t OP1, mp_bitcnt_t
  3033. OP2)
  3034. Set ROP to OP1 divided by 2 raised to OP2.
  3035. 
  3036. File: gmp.info, Node: Float Comparison, Next: I/O of Floats, Prev: Float Arithmetic, Up: Floating-point Functions
  3037. 7.6 Comparison Functions
  3038. ========================
  3039. -- Function: int mpf_cmp (const mpf_t OP1, const mpf_t OP2)
  3040. -- Function: int mpf_cmp_z (const mpf_t OP1, const mpz_t OP2)
  3041. -- Function: int mpf_cmp_d (const mpf_t OP1, double OP2)
  3042. -- Function: int mpf_cmp_ui (const mpf_t OP1, unsigned long int OP2)
  3043. -- Function: int mpf_cmp_si (const mpf_t OP1, signed long int OP2)
  3044. Compare OP1 and OP2. Return a positive value if OP1 > OP2, zero if
  3045. OP1 = OP2, and a negative value if OP1 < OP2.
  3046. 'mpf_cmp_d' can be called with an infinity, but results are
  3047. undefined for a NaN.
  3048. -- Function: int mpf_eq (const mpf_t OP1, const mpf_t OP2, mp_bitcnt_t
  3049. op3)
  3050. *This function is mathematically ill-defined and should not be
  3051. used.*
  3052. Return non-zero if the first OP3 bits of OP1 and OP2 are equal,
  3053. zero otherwise. Note that numbers like e.g., 256 (binary
  3054. 100000000) and 255 (binary 11111111) will never be equal by this
  3055. function's measure, and furthermore that 0 will only be equal to
  3056. itself.
  3057. -- Function: void mpf_reldiff (mpf_t ROP, const mpf_t OP1, const mpf_t
  3058. OP2)
  3059. Compute the relative difference between OP1 and OP2 and store the
  3060. result in ROP. This is abs(OP1-OP2)/OP1.
  3061. -- Macro: int mpf_sgn (const mpf_t OP)
  3062. Return +1 if OP > 0, 0 if OP = 0, and -1 if OP < 0.
  3063. This function is actually implemented as a macro. It evaluates its
  3064. argument multiple times.
  3065. 
  3066. File: gmp.info, Node: I/O of Floats, Next: Miscellaneous Float Functions, Prev: Float Comparison, Up: Floating-point Functions
  3067. 7.7 Input and Output Functions
  3068. ==============================
  3069. Functions that perform input from a stdio stream, and functions that
  3070. output to a stdio stream, of 'mpf' numbers. Passing a 'NULL' pointer
  3071. for a STREAM argument to any of these functions will make them read from
  3072. 'stdin' and write to 'stdout', respectively.
  3073. When using any of these functions, it is a good idea to include
  3074. 'stdio.h' before 'gmp.h', since that will allow 'gmp.h' to define
  3075. prototypes for these functions.
  3076. See also *note Formatted Output:: and *note Formatted Input::.
  3077. -- Function: size_t mpf_out_str (FILE *STREAM, int BASE, size_t
  3078. N_DIGITS, const mpf_t OP)
  3079. Print OP to STREAM, as a string of digits. Return the number of
  3080. bytes written, or if an error occurred, return 0.
  3081. The mantissa is prefixed with an '0.' and is in the given BASE,
  3082. which may vary from 2 to 62 or from -2 to -36. An exponent is then
  3083. printed, separated by an 'e', or if the base is greater than 10
  3084. then by an '@'. The exponent is always in decimal. The decimal
  3085. point follows the current locale, on systems providing
  3086. 'localeconv'.
  3087. For BASE in the range 2..36, digits and lower-case letters are
  3088. used; for -2..-36, digits and upper-case letters are used; for
  3089. 37..62, digits, upper-case letters, and lower-case letters (in that
  3090. significance order) are used.
  3091. Up to N_DIGITS will be printed from the mantissa, except that no
  3092. more digits than are accurately representable by OP will be
  3093. printed. N_DIGITS can be 0 to select that accurate maximum.
  3094. -- Function: size_t mpf_inp_str (mpf_t ROP, FILE *STREAM, int BASE)
  3095. Read a string in base BASE from STREAM, and put the read float in
  3096. ROP. The string is of the form 'M@N' or, if the base is 10 or
  3097. less, alternatively 'MeN'. 'M' is the mantissa and 'N' is the
  3098. exponent. The mantissa is always in the specified base. The
  3099. exponent is either in the specified base or, if BASE is negative,
  3100. in decimal. The decimal point expected is taken from the current
  3101. locale, on systems providing 'localeconv'.
  3102. The argument BASE may be in the ranges 2 to 36, or -36 to -2.
  3103. Negative values are used to specify that the exponent is in
  3104. decimal.
  3105. Unlike the corresponding 'mpz' function, the base will not be
  3106. determined from the leading characters of the string if BASE is 0.
  3107. This is so that numbers like '0.23' are not interpreted as octal.
  3108. Return the number of bytes read, or if an error occurred, return 0.
  3109. 
  3110. File: gmp.info, Node: Miscellaneous Float Functions, Prev: I/O of Floats, Up: Floating-point Functions
  3111. 7.8 Miscellaneous Functions
  3112. ===========================
  3113. -- Function: void mpf_ceil (mpf_t ROP, const mpf_t OP)
  3114. -- Function: void mpf_floor (mpf_t ROP, const mpf_t OP)
  3115. -- Function: void mpf_trunc (mpf_t ROP, const mpf_t OP)
  3116. Set ROP to OP rounded to an integer. 'mpf_ceil' rounds to the next
  3117. higher integer, 'mpf_floor' to the next lower, and 'mpf_trunc' to
  3118. the integer towards zero.
  3119. -- Function: int mpf_integer_p (const mpf_t OP)
  3120. Return non-zero if OP is an integer.
  3121. -- Function: int mpf_fits_ulong_p (const mpf_t OP)
  3122. -- Function: int mpf_fits_slong_p (const mpf_t OP)
  3123. -- Function: int mpf_fits_uint_p (const mpf_t OP)
  3124. -- Function: int mpf_fits_sint_p (const mpf_t OP)
  3125. -- Function: int mpf_fits_ushort_p (const mpf_t OP)
  3126. -- Function: int mpf_fits_sshort_p (const mpf_t OP)
  3127. Return non-zero if OP would fit in the respective C data type, when
  3128. truncated to an integer.
  3129. -- Function: void mpf_urandomb (mpf_t ROP, gmp_randstate_t STATE,
  3130. mp_bitcnt_t NBITS)
  3131. Generate a uniformly distributed random float in ROP, such that 0
  3132. <= ROP < 1, with NBITS significant bits in the mantissa or less if
  3133. the precision of ROP is smaller.
  3134. The variable STATE must be initialized by calling one of the
  3135. 'gmp_randinit' functions (*note Random State Initialization::)
  3136. before invoking this function.
  3137. -- Function: void mpf_random2 (mpf_t ROP, mp_size_t MAX_SIZE, mp_exp_t
  3138. EXP)
  3139. Generate a random float of at most MAX_SIZE limbs, with long
  3140. strings of zeros and ones in the binary representation. The
  3141. exponent of the number is in the interval -EXP to EXP (in limbs).
  3142. This function is useful for testing functions and algorithms, since
  3143. these kind of random numbers have proven to be more likely to
  3144. trigger corner-case bugs. Negative random numbers are generated
  3145. when MAX_SIZE is negative.
  3146. 
  3147. File: gmp.info, Node: Low-level Functions, Next: Random Number Functions, Prev: Floating-point Functions, Up: Top
  3148. 8 Low-level Functions
  3149. *********************
  3150. This chapter describes low-level GMP functions, used to implement the
  3151. high-level GMP functions, but also intended for time-critical user code.
  3152. These functions start with the prefix 'mpn_'.
  3153. The 'mpn' functions are designed to be as fast as possible, *not* to
  3154. provide a coherent calling interface. The different functions have
  3155. somewhat similar interfaces, but there are variations that make them
  3156. hard to use. These functions do as little as possible apart from the
  3157. real multiple precision computation, so that no time is spent on things
  3158. that not all callers need.
  3159. A source operand is specified by a pointer to the least significant
  3160. limb and a limb count. A destination operand is specified by just a
  3161. pointer. It is the responsibility of the caller to ensure that the
  3162. destination has enough space for storing the result.
  3163. With this way of specifying operands, it is possible to perform
  3164. computations on subranges of an argument, and store the result into a
  3165. subrange of a destination.
  3166. A common requirement for all functions is that each source area needs
  3167. at least one limb. No size argument may be zero. Unless otherwise
  3168. stated, in-place operations are allowed where source and destination are
  3169. the same, but not where they only partly overlap.
  3170. The 'mpn' functions are the base for the implementation of the
  3171. 'mpz_', 'mpf_', and 'mpq_' functions.
  3172. This example adds the number beginning at S1P and the number
  3173. beginning at S2P and writes the sum at DESTP. All areas have N limbs.
  3174. cy = mpn_add_n (destp, s1p, s2p, n)
  3175. It should be noted that the 'mpn' functions make no attempt to
  3176. identify high or low zero limbs on their operands, or other special
  3177. forms. On random data such cases will be unlikely and it'd be wasteful
  3178. for every function to check every time. An application knowing
  3179. something about its data can take steps to trim or perhaps split its
  3180. calculations.
  3181. In the notation used below, a source operand is identified by the
  3182. pointer to the least significant limb, and the limb count in braces.
  3183. For example, {S1P, S1N}.
  3184. -- Function: mp_limb_t mpn_add_n (mp_limb_t *RP, const mp_limb_t *S1P,
  3185. const mp_limb_t *S2P, mp_size_t N)
  3186. Add {S1P, N} and {S2P, N}, and write the N least significant limbs
  3187. of the result to RP. Return carry, either 0 or 1.
  3188. This is the lowest-level function for addition. It is the
  3189. preferred function for addition, since it is written in assembly
  3190. for most CPUs. For addition of a variable to itself (i.e., S1P
  3191. equals S2P) use 'mpn_lshift' with a count of 1 for optimal speed.
  3192. -- Function: mp_limb_t mpn_add_1 (mp_limb_t *RP, const mp_limb_t *S1P,
  3193. mp_size_t N, mp_limb_t S2LIMB)
  3194. Add {S1P, N} and S2LIMB, and write the N least significant limbs of
  3195. the result to RP. Return carry, either 0 or 1.
  3196. -- Function: mp_limb_t mpn_add (mp_limb_t *RP, const mp_limb_t *S1P,
  3197. mp_size_t S1N, const mp_limb_t *S2P, mp_size_t S2N)
  3198. Add {S1P, S1N} and {S2P, S2N}, and write the S1N least significant
  3199. limbs of the result to RP. Return carry, either 0 or 1.
  3200. This function requires that S1N is greater than or equal to S2N.
  3201. -- Function: mp_limb_t mpn_sub_n (mp_limb_t *RP, const mp_limb_t *S1P,
  3202. const mp_limb_t *S2P, mp_size_t N)
  3203. Subtract {S2P, N} from {S1P, N}, and write the N least significant
  3204. limbs of the result to RP. Return borrow, either 0 or 1.
  3205. This is the lowest-level function for subtraction. It is the
  3206. preferred function for subtraction, since it is written in assembly
  3207. for most CPUs.
  3208. -- Function: mp_limb_t mpn_sub_1 (mp_limb_t *RP, const mp_limb_t *S1P,
  3209. mp_size_t N, mp_limb_t S2LIMB)
  3210. Subtract S2LIMB from {S1P, N}, and write the N least significant
  3211. limbs of the result to RP. Return borrow, either 0 or 1.
  3212. -- Function: mp_limb_t mpn_sub (mp_limb_t *RP, const mp_limb_t *S1P,
  3213. mp_size_t S1N, const mp_limb_t *S2P, mp_size_t S2N)
  3214. Subtract {S2P, S2N} from {S1P, S1N}, and write the S1N least
  3215. significant limbs of the result to RP. Return borrow, either 0 or
  3216. 1.
  3217. This function requires that S1N is greater than or equal to S2N.
  3218. -- Function: mp_limb_t mpn_neg (mp_limb_t *RP, const mp_limb_t *SP,
  3219. mp_size_t N)
  3220. Perform the negation of {SP, N}, and write the result to {RP, N}.
  3221. This is equivalent to calling 'mpn_sub_n' with a N-limb zero
  3222. minuend and passing {SP, N} as subtrahend. Return borrow, either 0
  3223. or 1.
  3224. -- Function: void mpn_mul_n (mp_limb_t *RP, const mp_limb_t *S1P, const
  3225. mp_limb_t *S2P, mp_size_t N)
  3226. Multiply {S1P, N} and {S2P, N}, and write the 2*N-limb result to
  3227. RP.
  3228. The destination has to have space for 2*N limbs, even if the
  3229. product's most significant limb is zero. No overlap is permitted
  3230. between the destination and either source.
  3231. If the two input operands are the same, use 'mpn_sqr'.
  3232. -- Function: mp_limb_t mpn_mul (mp_limb_t *RP, const mp_limb_t *S1P,
  3233. mp_size_t S1N, const mp_limb_t *S2P, mp_size_t S2N)
  3234. Multiply {S1P, S1N} and {S2P, S2N}, and write the (S1N+S2N)-limb
  3235. result to RP. Return the most significant limb of the result.
  3236. The destination has to have space for S1N + S2N limbs, even if the
  3237. product's most significant limb is zero. No overlap is permitted
  3238. between the destination and either source.
  3239. This function requires that S1N is greater than or equal to S2N.
  3240. -- Function: void mpn_sqr (mp_limb_t *RP, const mp_limb_t *S1P,
  3241. mp_size_t N)
  3242. Compute the square of {S1P, N} and write the 2*N-limb result to RP.
  3243. The destination has to have space for 2N limbs, even if the
  3244. result's most significant limb is zero. No overlap is permitted
  3245. between the destination and the source.
  3246. -- Function: mp_limb_t mpn_mul_1 (mp_limb_t *RP, const mp_limb_t *S1P,
  3247. mp_size_t N, mp_limb_t S2LIMB)
  3248. Multiply {S1P, N} by S2LIMB, and write the N least significant
  3249. limbs of the product to RP. Return the most significant limb of
  3250. the product. {S1P, N} and {RP, N} are allowed to overlap provided
  3251. RP <= S1P.
  3252. This is a low-level function that is a building block for general
  3253. multiplication as well as other operations in GMP. It is written
  3254. in assembly for most CPUs.
  3255. Don't call this function if S2LIMB is a power of 2; use
  3256. 'mpn_lshift' with a count equal to the logarithm of S2LIMB instead,
  3257. for optimal speed.
  3258. -- Function: mp_limb_t mpn_addmul_1 (mp_limb_t *RP, const mp_limb_t
  3259. *S1P, mp_size_t N, mp_limb_t S2LIMB)
  3260. Multiply {S1P, N} and S2LIMB, and add the N least significant limbs
  3261. of the product to {RP, N} and write the result to RP. Return the
  3262. most significant limb of the product, plus carry-out from the
  3263. addition. {S1P, N} and {RP, N} are allowed to overlap provided RP
  3264. <= S1P.
  3265. This is a low-level function that is a building block for general
  3266. multiplication as well as other operations in GMP. It is written
  3267. in assembly for most CPUs.
  3268. -- Function: mp_limb_t mpn_submul_1 (mp_limb_t *RP, const mp_limb_t
  3269. *S1P, mp_size_t N, mp_limb_t S2LIMB)
  3270. Multiply {S1P, N} and S2LIMB, and subtract the N least significant
  3271. limbs of the product from {RP, N} and write the result to RP.
  3272. Return the most significant limb of the product, plus borrow-out
  3273. from the subtraction. {S1P, N} and {RP, N} are allowed to overlap
  3274. provided RP <= S1P.
  3275. This is a low-level function that is a building block for general
  3276. multiplication and division as well as other operations in GMP. It
  3277. is written in assembly for most CPUs.
  3278. -- Function: void mpn_tdiv_qr (mp_limb_t *QP, mp_limb_t *RP, mp_size_t
  3279. QXN, const mp_limb_t *NP, mp_size_t NN, const mp_limb_t *DP,
  3280. mp_size_t DN)
  3281. Divide {NP, NN} by {DP, DN} and put the quotient at {QP, NN-DN+1}
  3282. and the remainder at {RP, DN}. The quotient is rounded towards 0.
  3283. No overlap is permitted between arguments, except that NP might
  3284. equal RP. The dividend size NN must be greater than or equal to
  3285. divisor size DN. The most significant limb of the divisor must be
  3286. non-zero. The QXN operand must be zero.
  3287. -- Function: mp_limb_t mpn_divrem (mp_limb_t *R1P, mp_size_t QXN,
  3288. mp_limb_t *RS2P, mp_size_t RS2N, const mp_limb_t *S3P,
  3289. mp_size_t S3N)
  3290. [This function is obsolete. Please call 'mpn_tdiv_qr' instead for
  3291. best performance.]
  3292. Divide {RS2P, RS2N} by {S3P, S3N}, and write the quotient at R1P,
  3293. with the exception of the most significant limb, which is returned.
  3294. The remainder replaces the dividend at RS2P; it will be S3N limbs
  3295. long (i.e., as many limbs as the divisor).
  3296. In addition to an integer quotient, QXN fraction limbs are
  3297. developed, and stored after the integral limbs. For most usages,
  3298. QXN will be zero.
  3299. It is required that RS2N is greater than or equal to S3N. It is
  3300. required that the most significant bit of the divisor is set.
  3301. If the quotient is not needed, pass RS2P + S3N as R1P. Aside from
  3302. that special case, no overlap between arguments is permitted.
  3303. Return the most significant limb of the quotient, either 0 or 1.
  3304. The area at R1P needs to be RS2N - S3N + QXN limbs large.
  3305. -- Function: mp_limb_t mpn_divrem_1 (mp_limb_t *R1P, mp_size_t QXN,
  3306. mp_limb_t *S2P, mp_size_t S2N, mp_limb_t S3LIMB)
  3307. -- Macro: mp_limb_t mpn_divmod_1 (mp_limb_t *R1P, mp_limb_t *S2P,
  3308. mp_size_t S2N, mp_limb_t S3LIMB)
  3309. Divide {S2P, S2N} by S3LIMB, and write the quotient at R1P. Return
  3310. the remainder.
  3311. The integer quotient is written to {R1P+QXN, S2N} and in addition
  3312. QXN fraction limbs are developed and written to {R1P, QXN}. Either
  3313. or both S2N and QXN can be zero. For most usages, QXN will be
  3314. zero.
  3315. 'mpn_divmod_1' exists for upward source compatibility and is simply
  3316. a macro calling 'mpn_divrem_1' with a QXN of 0.
  3317. The areas at R1P and S2P have to be identical or completely
  3318. separate, not partially overlapping.
  3319. -- Function: mp_limb_t mpn_divmod (mp_limb_t *R1P, mp_limb_t *RS2P,
  3320. mp_size_t RS2N, const mp_limb_t *S3P, mp_size_t S3N)
  3321. [This function is obsolete. Please call 'mpn_tdiv_qr' instead for
  3322. best performance.]
  3323. -- Function: void mpn_divexact_1 (mp_limb_t * RP, const mp_limb_t * SP,
  3324. mp_size_t N, mp_limb_t D)
  3325. Divide {SP, N} by D, expecting it to divide exactly, and writing
  3326. the result to {RP, N}. If D doesn't divide exactly, the value
  3327. written to {RP, N} is undefined. The areas at RP and SP have to be
  3328. identical or completely separate, not partially overlapping.
  3329. -- Macro: mp_limb_t mpn_divexact_by3 (mp_limb_t *RP, mp_limb_t *SP,
  3330. mp_size_t N)
  3331. -- Function: mp_limb_t mpn_divexact_by3c (mp_limb_t *RP, mp_limb_t *SP,
  3332. mp_size_t N, mp_limb_t CARRY)
  3333. Divide {SP, N} by 3, expecting it to divide exactly, and writing
  3334. the result to {RP, N}. If 3 divides exactly, the return value is
  3335. zero and the result is the quotient. If not, the return value is
  3336. non-zero and the result won't be anything useful.
  3337. 'mpn_divexact_by3c' takes an initial carry parameter, which can be
  3338. the return value from a previous call, so a large calculation can
  3339. be done piece by piece from low to high. 'mpn_divexact_by3' is
  3340. simply a macro calling 'mpn_divexact_by3c' with a 0 carry
  3341. parameter.
  3342. These routines use a multiply-by-inverse and will be faster than
  3343. 'mpn_divrem_1' on CPUs with fast multiplication but slow division.
  3344. The source a, result q, size n, initial carry i, and return value c
  3345. satisfy c*b^n + a-i = 3*q, where b=2^GMP_NUMB_BITS. The return c is
  3346. always 0, 1 or 2, and the initial carry i must also be 0, 1 or 2
  3347. (these are both borrows really). When c=0 clearly q=(a-i)/3. When
  3348. c!=0, the remainder (a-i) mod 3 is given by 3-c, because b == 1 mod
  3349. 3 (when 'mp_bits_per_limb' is even, which is always so currently).
  3350. -- Function: mp_limb_t mpn_mod_1 (const mp_limb_t *S1P, mp_size_t S1N,
  3351. mp_limb_t S2LIMB)
  3352. Divide {S1P, S1N} by S2LIMB, and return the remainder. S1N can be
  3353. zero.
  3354. -- Function: mp_limb_t mpn_lshift (mp_limb_t *RP, const mp_limb_t *SP,
  3355. mp_size_t N, unsigned int COUNT)
  3356. Shift {SP, N} left by COUNT bits, and write the result to {RP, N}.
  3357. The bits shifted out at the left are returned in the least
  3358. significant COUNT bits of the return value (the rest of the return
  3359. value is zero).
  3360. COUNT must be in the range 1 to mp_bits_per_limb-1. The regions
  3361. {SP, N} and {RP, N} may overlap, provided RP >= SP.
  3362. This function is written in assembly for most CPUs.
  3363. -- Function: mp_limb_t mpn_rshift (mp_limb_t *RP, const mp_limb_t *SP,
  3364. mp_size_t N, unsigned int COUNT)
  3365. Shift {SP, N} right by COUNT bits, and write the result to {RP, N}.
  3366. The bits shifted out at the right are returned in the most
  3367. significant COUNT bits of the return value (the rest of the return
  3368. value is zero).
  3369. COUNT must be in the range 1 to mp_bits_per_limb-1. The regions
  3370. {SP, N} and {RP, N} may overlap, provided RP <= SP.
  3371. This function is written in assembly for most CPUs.
  3372. -- Function: int mpn_cmp (const mp_limb_t *S1P, const mp_limb_t *S2P,
  3373. mp_size_t N)
  3374. Compare {S1P, N} and {S2P, N} and return a positive value if S1 >
  3375. S2, 0 if they are equal, or a negative value if S1 < S2.
  3376. -- Function: int mpn_zero_p (const mp_limb_t *SP, mp_size_t N)
  3377. Test {SP, N} and return 1 if the operand is zero, 0 otherwise.
  3378. -- Function: mp_size_t mpn_gcd (mp_limb_t *RP, mp_limb_t *XP, mp_size_t
  3379. XN, mp_limb_t *YP, mp_size_t YN)
  3380. Set {RP, RETVAL} to the greatest common divisor of {XP, XN} and
  3381. {YP, YN}. The result can be up to YN limbs, the return value is
  3382. the actual number produced. Both source operands are destroyed.
  3383. It is required that XN >= YN > 0, and the most significant limb of
  3384. {YP, YN} must be non-zero. No overlap is permitted between {XP,
  3385. XN} and {YP, YN}.
  3386. -- Function: mp_limb_t mpn_gcd_1 (const mp_limb_t *XP, mp_size_t XN,
  3387. mp_limb_t YLIMB)
  3388. Return the greatest common divisor of {XP, XN} and YLIMB. Both
  3389. operands must be non-zero.
  3390. -- Function: mp_size_t mpn_gcdext (mp_limb_t *GP, mp_limb_t *SP,
  3391. mp_size_t *SN, mp_limb_t *UP, mp_size_t UN, mp_limb_t *VP,
  3392. mp_size_t VN)
  3393. Let U be defined by {UP, UN} and let V be defined by {VP, VN}.
  3394. Compute the greatest common divisor G of U and V. Compute a
  3395. cofactor S such that G = US + VT. The second cofactor T is not
  3396. computed but can easily be obtained from (G - U*S) / V (the
  3397. division will be exact). It is required that UN >= VN > 0, and the
  3398. most significant limb of {VP, VN} must be non-zero.
  3399. S satisfies S = 1 or abs(S) < V / (2 G). S = 0 if and only if V
  3400. divides U (i.e., G = V).
  3401. Store G at GP and let the return value define its limb count.
  3402. Store S at SP and let |*SN| define its limb count. S can be
  3403. negative; when this happens *SN will be negative. The area at GP
  3404. should have room for VN limbs and the area at SP should have room
  3405. for VN+1 limbs.
  3406. Both source operands are destroyed.
  3407. Compatibility notes: GMP 4.3.0 and 4.3.1 defined S less strictly.
  3408. Earlier as well as later GMP releases define S as described here.
  3409. GMP releases before GMP 4.3.0 required additional space for both
  3410. input and output areas. More precisely, the areas {UP, UN+1} and
  3411. {VP, VN+1} were destroyed (i.e. the operands plus an extra limb
  3412. past the end of each), and the areas pointed to by GP and SP should
  3413. each have room for UN+1 limbs.
  3414. -- Function: mp_size_t mpn_sqrtrem (mp_limb_t *R1P, mp_limb_t *R2P,
  3415. const mp_limb_t *SP, mp_size_t N)
  3416. Compute the square root of {SP, N} and put the result at {R1P,
  3417. ceil(N/2)} and the remainder at {R2P, RETVAL}. R2P needs space for
  3418. N limbs, but the return value indicates how many are produced.
  3419. The most significant limb of {SP, N} must be non-zero. The areas
  3420. {R1P, ceil(N/2)} and {SP, N} must be completely separate. The
  3421. areas {R2P, N} and {SP, N} must be either identical or completely
  3422. separate.
  3423. If the remainder is not wanted then R2P can be 'NULL', and in this
  3424. case the return value is zero or non-zero according to whether the
  3425. remainder would have been zero or non-zero.
  3426. A return value of zero indicates a perfect square. See also
  3427. 'mpn_perfect_square_p'.
  3428. -- Function: size_t mpn_sizeinbase (const mp_limb_t *XP, mp_size_t N,
  3429. int BASE)
  3430. Return the size of {XP,N} measured in number of digits in the given
  3431. BASE. BASE can vary from 2 to 62. Requires N > 0 and XP[N-1] > 0.
  3432. The result will be either exact or 1 too big. If BASE is a power
  3433. of 2, the result is always exact.
  3434. -- Function: mp_size_t mpn_get_str (unsigned char *STR, int BASE,
  3435. mp_limb_t *S1P, mp_size_t S1N)
  3436. Convert {S1P, S1N} to a raw unsigned char array at STR in base
  3437. BASE, and return the number of characters produced. There may be
  3438. leading zeros in the string. The string is not in ASCII; to
  3439. convert it to printable format, add the ASCII codes for '0' or 'A',
  3440. depending on the base and range. BASE can vary from 2 to 256.
  3441. The most significant limb of the input {S1P, S1N} must be non-zero.
  3442. The input {S1P, S1N} is clobbered, except when BASE is a power of
  3443. 2, in which case it's unchanged.
  3444. The area at STR has to have space for the largest possible number
  3445. represented by a S1N long limb array, plus one extra character.
  3446. -- Function: mp_size_t mpn_set_str (mp_limb_t *RP, const unsigned char
  3447. *STR, size_t STRSIZE, int BASE)
  3448. Convert bytes {STR,STRSIZE} in the given BASE to limbs at RP.
  3449. STR[0] is the most significant input byte and STR[STRSIZE-1] is the
  3450. least significant input byte. Each byte should be a value in the
  3451. range 0 to BASE-1, not an ASCII character. BASE can vary from 2 to
  3452. 256.
  3453. The converted value is {RP,RN} where RN is the return value. If
  3454. the most significant input byte STR[0] is non-zero, then RP[RN-1]
  3455. will be non-zero, else RP[RN-1] and some number of subsequent limbs
  3456. may be zero.
  3457. The area at RP has to have space for the largest possible number
  3458. with STRSIZE digits in the chosen base, plus one extra limb.
  3459. The input must have at least one byte, and no overlap is permitted
  3460. between {STR,STRSIZE} and the result at RP.
  3461. -- Function: mp_bitcnt_t mpn_scan0 (const mp_limb_t *S1P, mp_bitcnt_t
  3462. BIT)
  3463. Scan S1P from bit position BIT for the next clear bit.
  3464. It is required that there be a clear bit within the area at S1P at
  3465. or beyond bit position BIT, so that the function has something to
  3466. return.
  3467. -- Function: mp_bitcnt_t mpn_scan1 (const mp_limb_t *S1P, mp_bitcnt_t
  3468. BIT)
  3469. Scan S1P from bit position BIT for the next set bit.
  3470. It is required that there be a set bit within the area at S1P at or
  3471. beyond bit position BIT, so that the function has something to
  3472. return.
  3473. -- Function: void mpn_random (mp_limb_t *R1P, mp_size_t R1N)
  3474. -- Function: void mpn_random2 (mp_limb_t *R1P, mp_size_t R1N)
  3475. Generate a random number of length R1N and store it at R1P. The
  3476. most significant limb is always non-zero. 'mpn_random' generates
  3477. uniformly distributed limb data, 'mpn_random2' generates long
  3478. strings of zeros and ones in the binary representation.
  3479. 'mpn_random2' is intended for testing the correctness of the 'mpn'
  3480. routines.
  3481. -- Function: mp_bitcnt_t mpn_popcount (const mp_limb_t *S1P, mp_size_t
  3482. N)
  3483. Count the number of set bits in {S1P, N}.
  3484. -- Function: mp_bitcnt_t mpn_hamdist (const mp_limb_t *S1P, const
  3485. mp_limb_t *S2P, mp_size_t N)
  3486. Compute the hamming distance between {S1P, N} and {S2P, N}, which
  3487. is the number of bit positions where the two operands have
  3488. different bit values.
  3489. -- Function: int mpn_perfect_square_p (const mp_limb_t *S1P, mp_size_t
  3490. N)
  3491. Return non-zero iff {S1P, N} is a perfect square. The most
  3492. significant limb of the input {S1P, N} must be non-zero.
  3493. -- Function: void mpn_and_n (mp_limb_t *RP, const mp_limb_t *S1P, const
  3494. mp_limb_t *S2P, mp_size_t N)
  3495. Perform the bitwise logical and of {S1P, N} and {S2P, N}, and write
  3496. the result to {RP, N}.
  3497. -- Function: void mpn_ior_n (mp_limb_t *RP, const mp_limb_t *S1P, const
  3498. mp_limb_t *S2P, mp_size_t N)
  3499. Perform the bitwise logical inclusive or of {S1P, N} and {S2P, N},
  3500. and write the result to {RP, N}.
  3501. -- Function: void mpn_xor_n (mp_limb_t *RP, const mp_limb_t *S1P, const
  3502. mp_limb_t *S2P, mp_size_t N)
  3503. Perform the bitwise logical exclusive or of {S1P, N} and {S2P, N},
  3504. and write the result to {RP, N}.
  3505. -- Function: void mpn_andn_n (mp_limb_t *RP, const mp_limb_t *S1P,
  3506. const mp_limb_t *S2P, mp_size_t N)
  3507. Perform the bitwise logical and of {S1P, N} and the bitwise
  3508. complement of {S2P, N}, and write the result to {RP, N}.
  3509. -- Function: void mpn_iorn_n (mp_limb_t *RP, const mp_limb_t *S1P,
  3510. const mp_limb_t *S2P, mp_size_t N)
  3511. Perform the bitwise logical inclusive or of {S1P, N} and the
  3512. bitwise complement of {S2P, N}, and write the result to {RP, N}.
  3513. -- Function: void mpn_nand_n (mp_limb_t *RP, const mp_limb_t *S1P,
  3514. const mp_limb_t *S2P, mp_size_t N)
  3515. Perform the bitwise logical and of {S1P, N} and {S2P, N}, and write
  3516. the bitwise complement of the result to {RP, N}.
  3517. -- Function: void mpn_nior_n (mp_limb_t *RP, const mp_limb_t *S1P,
  3518. const mp_limb_t *S2P, mp_size_t N)
  3519. Perform the bitwise logical inclusive or of {S1P, N} and {S2P, N},
  3520. and write the bitwise complement of the result to {RP, N}.
  3521. -- Function: void mpn_xnor_n (mp_limb_t *RP, const mp_limb_t *S1P,
  3522. const mp_limb_t *S2P, mp_size_t N)
  3523. Perform the bitwise logical exclusive or of {S1P, N} and {S2P, N},
  3524. and write the bitwise complement of the result to {RP, N}.
  3525. -- Function: void mpn_com (mp_limb_t *RP, const mp_limb_t *SP,
  3526. mp_size_t N)
  3527. Perform the bitwise complement of {SP, N}, and write the result to
  3528. {RP, N}.
  3529. -- Function: void mpn_copyi (mp_limb_t *RP, const mp_limb_t *S1P,
  3530. mp_size_t N)
  3531. Copy from {S1P, N} to {RP, N}, increasingly.
  3532. -- Function: void mpn_copyd (mp_limb_t *RP, const mp_limb_t *S1P,
  3533. mp_size_t N)
  3534. Copy from {S1P, N} to {RP, N}, decreasingly.
  3535. -- Function: void mpn_zero (mp_limb_t *RP, mp_size_t N)
  3536. Zero {RP, N}.
  3537. 8.1 Low-level functions for cryptography
  3538. ========================================
  3539. The functions prefixed with 'mpn_sec_' and 'mpn_cnd_' are designed to
  3540. perform the exact same low-level operations and have the same cache
  3541. access patterns for any two same-size arguments, assuming that function
  3542. arguments are placed at the same position and that the machine state is
  3543. identical upon function entry. These functions are intended for
  3544. cryptographic purposes, where resilience to side-channel attacks is
  3545. desired.
  3546. These functions are less efficient than their "leaky" counterparts;
  3547. their performance for operands of the sizes typically used for
  3548. cryptographic applications is between 15% and 100% worse. For larger
  3549. operands, these functions might be inadequate, since they rely on
  3550. asymptotically elementary algorithms.
  3551. These functions do not make any explicit allocations. Those of these
  3552. functions that need scratch space accept a scratch space operand. This
  3553. convention allows callers to keep sensitive data in designated memory
  3554. areas. Note however that compilers may choose to spill scalar values
  3555. used within these functions to their stack frame and that such scalars
  3556. may contain sensitive data.
  3557. In addition to these specially crafted functions, the following 'mpn'
  3558. functions are naturally side-channel resistant: 'mpn_add_n',
  3559. 'mpn_sub_n', 'mpn_lshift', 'mpn_rshift', 'mpn_zero', 'mpn_copyi',
  3560. 'mpn_copyd', 'mpn_com', and the logical function ('mpn_and_n', etc).
  3561. There are some exceptions from the side-channel resilience: (1) Some
  3562. assembly implementations of 'mpn_lshift' identify shift-by-one as a
  3563. special case. This is a problem iff the shift count is a function of
  3564. sensitive data. (2) Alpha ev6 and Pentium4 using 64-bit limbs have
  3565. leaky 'mpn_add_n' and 'mpn_sub_n'. (3) Alpha ev6 has a leaky
  3566. 'mpn_mul_1' which also makes 'mpn_sec_mul' on those systems unsafe.
  3567. -- Function: mp_limb_t mpn_cnd_add_n (mp_limb_t CND, mp_limb_t *RP,
  3568. const mp_limb_t *S1P, const mp_limb_t *S2P, mp_size_t N)
  3569. -- Function: mp_limb_t mpn_cnd_sub_n (mp_limb_t CND, mp_limb_t *RP,
  3570. const mp_limb_t *S1P, const mp_limb_t *S2P, mp_size_t N)
  3571. These functions do conditional addition and subtraction. If CND is
  3572. non-zero, they produce the same result as a regular 'mpn_add_n' or
  3573. 'mpn_sub_n', and if CND is zero, they copy {S1P,N} to the result
  3574. area and return zero. The functions are designed to have timing
  3575. and memory access patterns depending only on size and location of
  3576. the data areas, but independent of the condition CND. Like for
  3577. 'mpn_add_n' and 'mpn_sub_n', on most machines, the timing will also
  3578. be independent of the actual limb values.
  3579. -- Function: mp_limb_t mpn_sec_add_1 (mp_limb_t *RP, const mp_limb_t
  3580. *AP, mp_size_t N, mp_limb_t B, mp_limb_t *TP)
  3581. -- Function: mp_limb_t mpn_sec_sub_1 (mp_limb_t *RP, const mp_limb_t
  3582. *AP, mp_size_t N, mp_limb_t B, mp_limb_t *TP)
  3583. Set R to A + B or A - B, respectively, where R = {RP,N}, A =
  3584. {AP,N}, and B is a single limb. Returns carry.
  3585. These functions take O(N) time, unlike the leaky functions
  3586. 'mpn_add_1' which are O(1) on average. They require scratch space
  3587. of 'mpn_sec_add_1_itch(N)' and 'mpn_sec_sub_1_itch(N)' limbs,
  3588. respectively, to be passed in the TP parameter. The scratch space
  3589. requirements are guaranteed to be at most N limbs, and increase
  3590. monotonously in the operand size.
  3591. -- Function: void mpn_cnd_swap (mp_limb_t CND, volatile mp_limb_t *AP,
  3592. volatile mp_limb_t *BP, mp_size_t N)
  3593. If CND is non-zero, swaps the contents of the areas {AP,N} and
  3594. {BP,N}. Otherwise, the areas are left unmodified. Implemented
  3595. using logical operations on the limbs, with the same memory
  3596. accesses independent of the value of CND.
  3597. -- Function: void mpn_sec_mul (mp_limb_t *RP, const mp_limb_t *AP,
  3598. mp_size_t AN, const mp_limb_t *BP, mp_size_t BN, mp_limb_t
  3599. *TP)
  3600. -- Function: mp_size_t mpn_sec_mul_itch (mp_size_t AN, mp_size_t BN)
  3601. Set R to A * B, where A = {AP,AN}, B = {BP,BN}, and R = {RP,AN+BN}.
  3602. It is required that AN >= BN > 0.
  3603. No overlapping between R and the input operands is allowed. For A
  3604. = B, use 'mpn_sec_sqr' for optimal performance.
  3605. This function requires scratch space of 'mpn_sec_mul_itch(AN, BN)'
  3606. limbs to be passed in the TP parameter. The scratch space
  3607. requirements are guaranteed to increase monotonously in the operand
  3608. sizes.
  3609. -- Function: void mpn_sec_sqr (mp_limb_t *RP, const mp_limb_t *AP,
  3610. mp_size_t AN, mp_limb_t *TP)
  3611. -- Function: mp_size_t mpn_sec_sqr_itch (mp_size_t AN)
  3612. Set R to A^2, where A = {AP,AN}, and R = {RP,2AN}.
  3613. It is required that AN > 0.
  3614. No overlapping between R and the input operands is allowed.
  3615. This function requires scratch space of 'mpn_sec_sqr_itch(AN)'
  3616. limbs to be passed in the TP parameter. The scratch space
  3617. requirements are guaranteed to increase monotonously in the operand
  3618. size.
  3619. -- Function: void mpn_sec_powm (mp_limb_t *RP, const mp_limb_t *BP,
  3620. mp_size_t BN, const mp_limb_t *EP, mp_bitcnt_t ENB, const
  3621. mp_limb_t *MP, mp_size_t N, mp_limb_t *TP)
  3622. -- Function: mp_size_t mpn_sec_powm_itch (mp_size_t BN, mp_bitcnt_t
  3623. ENB, size_t N)
  3624. Set R to (B raised to E) modulo M, where R = {RP,N}, M = {MP,N},
  3625. and E = {EP,ceil(ENB / 'GMP\_NUMB\_BITS')}.
  3626. It is required that B > 0, that M > 0 is odd, and that E < 2^ENB.
  3627. No overlapping between R and the input operands is allowed.
  3628. This function requires scratch space of 'mpn_sec_powm_itch(BN, ENB,
  3629. N)' limbs to be passed in the TP parameter. The scratch space
  3630. requirements are guaranteed to increase monotonously in the operand
  3631. sizes.
  3632. -- Function: void mpn_sec_tabselect (mp_limb_t *RP, const mp_limb_t
  3633. *TAB, mp_size_t N, mp_size_t NENTS, mp_size_t WHICH)
  3634. Select entry WHICH from table TAB, which has NENTS entries, each N
  3635. limbs. Store the selected entry at RP.
  3636. This function reads the entire table to avoid side-channel
  3637. information leaks.
  3638. -- Function: mp_limb_t mpn_sec_div_qr (mp_limb_t *QP, mp_limb_t *NP,
  3639. mp_size_t NN, const mp_limb_t *DP, mp_size_t DN, mp_limb_t
  3640. *TP)
  3641. -- Function: mp_size_t mpn_sec_div_qr_itch (mp_size_t NN, mp_size_t DN)
  3642. Set Q to the truncated quotient N / D and R to N modulo D, where N
  3643. = {NP,NN}, D = {DP,DN}, Q's most significant limb is the function
  3644. return value and the remaining limbs are {QP,NN-DN}, and R =
  3645. {NP,DN}.
  3646. It is required that NN >= DN >= 1, and that DP[DN-1] != 0. This
  3647. does not imply that N >= D since N might be zero-padded.
  3648. Note the overlapping between N and R. No other operand overlapping
  3649. is allowed. The entire space occupied by N is overwritten.
  3650. This function requires scratch space of 'mpn_sec_div_qr_itch(NN,
  3651. DN)' limbs to be passed in the TP parameter.
  3652. -- Function: void mpn_sec_div_r (mp_limb_t *NP, mp_size_t NN, const
  3653. mp_limb_t *DP, mp_size_t DN, mp_limb_t *TP)
  3654. -- Function: mp_size_t mpn_sec_div_r_itch (mp_size_t NN, mp_size_t DN)
  3655. Set R to N modulo D, where N = {NP,NN}, D = {DP,DN}, and R =
  3656. {NP,DN}.
  3657. It is required that NN >= DN >= 1, and that DP[DN-1] != 0. This
  3658. does not imply that N >= D since N might be zero-padded.
  3659. Note the overlapping between N and R. No other operand overlapping
  3660. is allowed. The entire space occupied by N is overwritten.
  3661. This function requires scratch space of 'mpn_sec_div_r_itch(NN,
  3662. DN)' limbs to be passed in the TP parameter.
  3663. -- Function: int mpn_sec_invert (mp_limb_t *RP, mp_limb_t *AP, const
  3664. mp_limb_t *MP, mp_size_t N, mp_bitcnt_t NBCNT, mp_limb_t *TP)
  3665. -- Function: mp_size_t mpn_sec_invert_itch (mp_size_t N)
  3666. Set R to the inverse of A modulo M, where R = {RP,N}, A = {AP,N},
  3667. and M = {MP,N}. *This function's interface is preliminary.*
  3668. If an inverse exists, return 1, otherwise return 0 and leave R
  3669. undefined. In either case, the input A is destroyed.
  3670. It is required that M is odd, and that NBCNT >= ceil(\log(A+1)) +
  3671. ceil(\log(M+1)). A safe choice is NBCNT = 2 * N * GMP_NUMB_BITS,
  3672. but a smaller value might improve performance if M or A are known
  3673. to have leading zero bits.
  3674. This function requires scratch space of 'mpn_sec_invert_itch(N)'
  3675. limbs to be passed in the TP parameter.
  3676. 8.2 Nails
  3677. =========
  3678. *Everything in this section is highly experimental and may disappear or
  3679. be subject to incompatible changes in a future version of GMP.*
  3680. Nails are an experimental feature whereby a few bits are left unused
  3681. at the top of each 'mp_limb_t'. This can significantly improve carry
  3682. handling on some processors.
  3683. All the 'mpn' functions accepting limb data will expect the nail bits
  3684. to be zero on entry, and will return data with the nails similarly all
  3685. zero. This applies both to limb vectors and to single limb arguments.
  3686. Nails can be enabled by configuring with '--enable-nails'. By
  3687. default the number of bits will be chosen according to what suits the
  3688. host processor, but a particular number can be selected with
  3689. '--enable-nails=N'.
  3690. At the mpn level, a nail build is neither source nor binary
  3691. compatible with a non-nail build, strictly speaking. But programs
  3692. acting on limbs only through the mpn functions are likely to work
  3693. equally well with either build, and judicious use of the definitions
  3694. below should make any program compatible with either build, at the
  3695. source level.
  3696. For the higher level routines, meaning 'mpz' etc, a nail build should
  3697. be fully source and binary compatible with a non-nail build.
  3698. -- Macro: GMP_NAIL_BITS
  3699. -- Macro: GMP_NUMB_BITS
  3700. -- Macro: GMP_LIMB_BITS
  3701. 'GMP_NAIL_BITS' is the number of nail bits, or 0 when nails are not
  3702. in use. 'GMP_NUMB_BITS' is the number of data bits in a limb.
  3703. 'GMP_LIMB_BITS' is the total number of bits in an 'mp_limb_t'. In
  3704. all cases
  3705. GMP_LIMB_BITS == GMP_NAIL_BITS + GMP_NUMB_BITS
  3706. -- Macro: GMP_NAIL_MASK
  3707. -- Macro: GMP_NUMB_MASK
  3708. Bit masks for the nail and number parts of a limb. 'GMP_NAIL_MASK'
  3709. is 0 when nails are not in use.
  3710. 'GMP_NAIL_MASK' is not often needed, since the nail part can be
  3711. obtained with 'x >> GMP_NUMB_BITS', and that means one less large
  3712. constant, which can help various RISC chips.
  3713. -- Macro: GMP_NUMB_MAX
  3714. The maximum value that can be stored in the number part of a limb.
  3715. This is the same as 'GMP_NUMB_MASK', but can be used for clarity
  3716. when doing comparisons rather than bit-wise operations.
  3717. The term "nails" comes from finger or toe nails, which are at the
  3718. ends of a limb (arm or leg). "numb" is short for number, but is also
  3719. how the developers felt after trying for a long time to come up with
  3720. sensible names for these things.
  3721. In the future (the distant future most likely) a non-zero nail might
  3722. be permitted, giving non-unique representations for numbers in a limb
  3723. vector. This would help vector processors since carries would only ever
  3724. need to propagate one or two limbs.
  3725. 
  3726. File: gmp.info, Node: Random Number Functions, Next: Formatted Output, Prev: Low-level Functions, Up: Top
  3727. 9 Random Number Functions
  3728. *************************
  3729. Sequences of pseudo-random numbers in GMP are generated using a variable
  3730. of type 'gmp_randstate_t', which holds an algorithm selection and a
  3731. current state. Such a variable must be initialized by a call to one of
  3732. the 'gmp_randinit' functions, and can be seeded with one of the
  3733. 'gmp_randseed' functions.
  3734. The functions actually generating random numbers are described in
  3735. *note Integer Random Numbers::, and *note Miscellaneous Float
  3736. Functions::.
  3737. The older style random number functions don't accept a
  3738. 'gmp_randstate_t' parameter but instead share a global variable of that
  3739. type. They use a default algorithm and are currently not seeded (though
  3740. perhaps that will change in the future). The new functions accepting a
  3741. 'gmp_randstate_t' are recommended for applications that care about
  3742. randomness.
  3743. * Menu:
  3744. * Random State Initialization::
  3745. * Random State Seeding::
  3746. * Random State Miscellaneous::
  3747. 
  3748. File: gmp.info, Node: Random State Initialization, Next: Random State Seeding, Prev: Random Number Functions, Up: Random Number Functions
  3749. 9.1 Random State Initialization
  3750. ===============================
  3751. -- Function: void gmp_randinit_default (gmp_randstate_t STATE)
  3752. Initialize STATE with a default algorithm. This will be a
  3753. compromise between speed and randomness, and is recommended for
  3754. applications with no special requirements. Currently this is
  3755. 'gmp_randinit_mt'.
  3756. -- Function: void gmp_randinit_mt (gmp_randstate_t STATE)
  3757. Initialize STATE for a Mersenne Twister algorithm. This algorithm
  3758. is fast and has good randomness properties.
  3759. -- Function: void gmp_randinit_lc_2exp (gmp_randstate_t STATE, const
  3760. mpz_t A, unsigned long C, mp_bitcnt_t M2EXP)
  3761. Initialize STATE with a linear congruential algorithm X = (A*X + C)
  3762. mod 2^M2EXP.
  3763. The low bits of X in this algorithm are not very random. The least
  3764. significant bit will have a period no more than 2, and the second
  3765. bit no more than 4, etc. For this reason only the high half of
  3766. each X is actually used.
  3767. When a random number of more than M2EXP/2 bits is to be generated,
  3768. multiple iterations of the recurrence are used and the results
  3769. concatenated.
  3770. -- Function: int gmp_randinit_lc_2exp_size (gmp_randstate_t STATE,
  3771. mp_bitcnt_t SIZE)
  3772. Initialize STATE for a linear congruential algorithm as per
  3773. 'gmp_randinit_lc_2exp'. A, C and M2EXP are selected from a table,
  3774. chosen so that SIZE bits (or more) of each X will be used, i.e.
  3775. M2EXP/2 >= SIZE.
  3776. If successful the return value is non-zero. If SIZE is bigger than
  3777. the table data provides then the return value is zero. The maximum
  3778. SIZE currently supported is 128.
  3779. -- Function: void gmp_randinit_set (gmp_randstate_t ROP,
  3780. gmp_randstate_t OP)
  3781. Initialize ROP with a copy of the algorithm and state from OP.
  3782. -- Function: void gmp_randinit (gmp_randstate_t STATE,
  3783. gmp_randalg_t ALG, ...)
  3784. *This function is obsolete.*
  3785. Initialize STATE with an algorithm selected by ALG. The only
  3786. choice is 'GMP_RAND_ALG_LC', which is 'gmp_randinit_lc_2exp_size'
  3787. described above. A third parameter of type 'unsigned long' is
  3788. required, this is the SIZE for that function.
  3789. 'GMP_RAND_ALG_DEFAULT' or 0 are the same as 'GMP_RAND_ALG_LC'.
  3790. 'gmp_randinit' sets bits in the global variable 'gmp_errno' to
  3791. indicate an error. 'GMP_ERROR_UNSUPPORTED_ARGUMENT' if ALG is
  3792. unsupported, or 'GMP_ERROR_INVALID_ARGUMENT' if the SIZE parameter
  3793. is too big. It may be noted this error reporting is not thread
  3794. safe (a good reason to use 'gmp_randinit_lc_2exp_size' instead).
  3795. -- Function: void gmp_randclear (gmp_randstate_t STATE)
  3796. Free all memory occupied by STATE.
  3797. 
  3798. File: gmp.info, Node: Random State Seeding, Next: Random State Miscellaneous, Prev: Random State Initialization, Up: Random Number Functions
  3799. 9.2 Random State Seeding
  3800. ========================
  3801. -- Function: void gmp_randseed (gmp_randstate_t STATE, const mpz_t
  3802. SEED)
  3803. -- Function: void gmp_randseed_ui (gmp_randstate_t STATE,
  3804. unsigned long int SEED)
  3805. Set an initial seed value into STATE.
  3806. The size of a seed determines how many different sequences of
  3807. random numbers that it's possible to generate. The "quality" of
  3808. the seed is the randomness of a given seed compared to the previous
  3809. seed used, and this affects the randomness of separate number
  3810. sequences. The method for choosing a seed is critical if the
  3811. generated numbers are to be used for important applications, such
  3812. as generating cryptographic keys.
  3813. Traditionally the system time has been used to seed, but care needs
  3814. to be taken with this. If an application seeds often and the
  3815. resolution of the system clock is low, then the same sequence of
  3816. numbers might be repeated. Also, the system time is quite easy to
  3817. guess, so if unpredictability is required then it should definitely
  3818. not be the only source for the seed value. On some systems there's
  3819. a special device '/dev/random' which provides random data better
  3820. suited for use as a seed.
  3821. 
  3822. File: gmp.info, Node: Random State Miscellaneous, Prev: Random State Seeding, Up: Random Number Functions
  3823. 9.3 Random State Miscellaneous
  3824. ==============================
  3825. -- Function: unsigned long gmp_urandomb_ui (gmp_randstate_t STATE,
  3826. unsigned long N)
  3827. Return a uniformly distributed random number of N bits, i.e. in the
  3828. range 0 to 2^N-1 inclusive. N must be less than or equal to the
  3829. number of bits in an 'unsigned long'.
  3830. -- Function: unsigned long gmp_urandomm_ui (gmp_randstate_t STATE,
  3831. unsigned long N)
  3832. Return a uniformly distributed random number in the range 0 to N-1,
  3833. inclusive.
  3834. 
  3835. File: gmp.info, Node: Formatted Output, Next: Formatted Input, Prev: Random Number Functions, Up: Top
  3836. 10 Formatted Output
  3837. *******************
  3838. * Menu:
  3839. * Formatted Output Strings::
  3840. * Formatted Output Functions::
  3841. * C++ Formatted Output::
  3842. 
  3843. File: gmp.info, Node: Formatted Output Strings, Next: Formatted Output Functions, Prev: Formatted Output, Up: Formatted Output
  3844. 10.1 Format Strings
  3845. ===================
  3846. 'gmp_printf' and friends accept format strings similar to the standard C
  3847. 'printf' (*note Formatted Output: (libc)Formatted Output.). A format
  3848. specification is of the form
  3849. % [flags] [width] [.[precision]] [type] conv
  3850. GMP adds types 'Z', 'Q' and 'F' for 'mpz_t', 'mpq_t' and 'mpf_t'
  3851. respectively, 'M' for 'mp_limb_t', and 'N' for an 'mp_limb_t' array.
  3852. 'Z', 'Q', 'M' and 'N' behave like integers. 'Q' will print a '/' and a
  3853. denominator, if needed. 'F' behaves like a float. For example,
  3854. mpz_t z;
  3855. gmp_printf ("%s is an mpz %Zd\n", "here", z);
  3856. mpq_t q;
  3857. gmp_printf ("a hex rational: %#40Qx\n", q);
  3858. mpf_t f;
  3859. int n;
  3860. gmp_printf ("fixed point mpf %.*Ff with %d digits\n", n, f, n);
  3861. mp_limb_t l;
  3862. gmp_printf ("limb %Mu\n", l);
  3863. const mp_limb_t *ptr;
  3864. mp_size_t size;
  3865. gmp_printf ("limb array %Nx\n", ptr, size);
  3866. For 'N' the limbs are expected least significant first, as per the
  3867. 'mpn' functions (*note Low-level Functions::). A negative size can be
  3868. given to print the value as a negative.
  3869. All the standard C 'printf' types behave the same as the C library
  3870. 'printf', and can be freely intermixed with the GMP extensions. In the
  3871. current implementation the standard parts of the format string are
  3872. simply handed to 'printf' and only the GMP extensions handled directly.
  3873. The flags accepted are as follows. GLIBC style ' is only for the
  3874. standard C types (not the GMP types), and only if the C library supports
  3875. it.
  3876. 0 pad with zeros (rather than spaces)
  3877. # show the base with '0x', '0X' or '0'
  3878. + always show a sign
  3879. (space) show a space or a '-' sign
  3880. ' group digits, GLIBC style (not GMP
  3881. types)
  3882. The optional width and precision can be given as a number within the
  3883. format string, or as a '*' to take an extra parameter of type 'int', the
  3884. same as the standard 'printf'.
  3885. The standard types accepted are as follows. 'h' and 'l' are
  3886. portable, the rest will depend on the compiler (or include files) for
  3887. the type and the C library for the output.
  3888. h short
  3889. hh char
  3890. j intmax_t or uintmax_t
  3891. l long or wchar_t
  3892. ll long long
  3893. L long double
  3894. q quad_t or u_quad_t
  3895. t ptrdiff_t
  3896. z size_t
  3897. The GMP types are
  3898. F mpf_t, float conversions
  3899. Q mpq_t, integer conversions
  3900. M mp_limb_t, integer conversions
  3901. N mp_limb_t array, integer conversions
  3902. Z mpz_t, integer conversions
  3903. The conversions accepted are as follows. 'a' and 'A' are always
  3904. supported for 'mpf_t' but depend on the C library for standard C float
  3905. types. 'm' and 'p' depend on the C library.
  3906. a A hex floats, C99 style
  3907. c character
  3908. d decimal integer
  3909. e E scientific format float
  3910. f fixed point float
  3911. i same as d
  3912. g G fixed or scientific float
  3913. m 'strerror' string, GLIBC style
  3914. n store characters written so far
  3915. o octal integer
  3916. p pointer
  3917. s string
  3918. u unsigned integer
  3919. x X hex integer
  3920. 'o', 'x' and 'X' are unsigned for the standard C types, but for types
  3921. 'Z', 'Q' and 'N' they are signed. 'u' is not meaningful for 'Z', 'Q'
  3922. and 'N'.
  3923. 'M' is a proxy for the C library 'l' or 'L', according to the size of
  3924. 'mp_limb_t'. Unsigned conversions will be usual, but a signed
  3925. conversion can be used and will interpret the value as a twos complement
  3926. negative.
  3927. 'n' can be used with any type, even the GMP types.
  3928. Other types or conversions that might be accepted by the C library
  3929. 'printf' cannot be used through 'gmp_printf', this includes for instance
  3930. extensions registered with GLIBC 'register_printf_function'. Also
  3931. currently there's no support for POSIX '$' style numbered arguments
  3932. (perhaps this will be added in the future).
  3933. The precision field has its usual meaning for integer 'Z' and float
  3934. 'F' types, but is currently undefined for 'Q' and should not be used
  3935. with that.
  3936. 'mpf_t' conversions only ever generate as many digits as can be
  3937. accurately represented by the operand, the same as 'mpf_get_str' does.
  3938. Zeros will be used if necessary to pad to the requested precision. This
  3939. happens even for an 'f' conversion of an 'mpf_t' which is an integer,
  3940. for instance 2^1024 in an 'mpf_t' of 128 bits precision will only
  3941. produce about 40 digits, then pad with zeros to the decimal point. An
  3942. empty precision field like '%.Fe' or '%.Ff' can be used to specifically
  3943. request just the significant digits. Without any dot and thus no
  3944. precision field, a precision value of 6 will be used. Note that these
  3945. rules mean that '%Ff', '%.Ff', and '%.0Ff' will all be different.
  3946. The decimal point character (or string) is taken from the current
  3947. locale settings on systems which provide 'localeconv' (*note Locales and
  3948. Internationalization: (libc)Locales.). The C library will normally do
  3949. the same for standard float output.
  3950. The format string is only interpreted as plain 'char's, multibyte
  3951. characters are not recognised. Perhaps this will change in the future.
  3952. 
  3953. File: gmp.info, Node: Formatted Output Functions, Next: C++ Formatted Output, Prev: Formatted Output Strings, Up: Formatted Output
  3954. 10.2 Functions
  3955. ==============
  3956. Each of the following functions is similar to the corresponding C
  3957. library function. The basic 'printf' forms take a variable argument
  3958. list. The 'vprintf' forms take an argument pointer, see *note Variadic
  3959. Functions: (libc)Variadic Functions, or 'man 3 va_start'.
  3960. It should be emphasised that if a format string is invalid, or the
  3961. arguments don't match what the format specifies, then the behaviour of
  3962. any of these functions will be unpredictable. GCC format string
  3963. checking is not available, since it doesn't recognise the GMP
  3964. extensions.
  3965. The file based functions 'gmp_printf' and 'gmp_fprintf' will return
  3966. -1 to indicate a write error. Output is not "atomic", so partial output
  3967. may be produced if a write error occurs. All the functions can return
  3968. -1 if the C library 'printf' variant in use returns -1, but this
  3969. shouldn't normally occur.
  3970. -- Function: int gmp_printf (const char *FMT, ...)
  3971. -- Function: int gmp_vprintf (const char *FMT, va_list AP)
  3972. Print to the standard output 'stdout'. Return the number of
  3973. characters written, or -1 if an error occurred.
  3974. -- Function: int gmp_fprintf (FILE *FP, const char *FMT, ...)
  3975. -- Function: int gmp_vfprintf (FILE *FP, const char *FMT, va_list AP)
  3976. Print to the stream FP. Return the number of characters written,
  3977. or -1 if an error occurred.
  3978. -- Function: int gmp_sprintf (char *BUF, const char *FMT, ...)
  3979. -- Function: int gmp_vsprintf (char *BUF, const char *FMT, va_list AP)
  3980. Form a null-terminated string in BUF. Return the number of
  3981. characters written, excluding the terminating null.
  3982. No overlap is permitted between the space at BUF and the string
  3983. FMT.
  3984. These functions are not recommended, since there's no protection
  3985. against exceeding the space available at BUF.
  3986. -- Function: int gmp_snprintf (char *BUF, size_t SIZE, const char *FMT,
  3987. ...)
  3988. -- Function: int gmp_vsnprintf (char *BUF, size_t SIZE, const char
  3989. *FMT, va_list AP)
  3990. Form a null-terminated string in BUF. No more than SIZE bytes will
  3991. be written. To get the full output, SIZE must be enough for the
  3992. string and null-terminator.
  3993. The return value is the total number of characters which ought to
  3994. have been produced, excluding the terminating null. If RETVAL >=
  3995. SIZE then the actual output has been truncated to the first SIZE-1
  3996. characters, and a null appended.
  3997. No overlap is permitted between the region {BUF,SIZE} and the FMT
  3998. string.
  3999. Notice the return value is in ISO C99 'snprintf' style. This is so
  4000. even if the C library 'vsnprintf' is the older GLIBC 2.0.x style.
  4001. -- Function: int gmp_asprintf (char **PP, const char *FMT, ...)
  4002. -- Function: int gmp_vasprintf (char **PP, const char *FMT, va_list AP)
  4003. Form a null-terminated string in a block of memory obtained from
  4004. the current memory allocation function (*note Custom Allocation::).
  4005. The block will be the size of the string and null-terminator. The
  4006. address of the block in stored to *PP. The return value is the
  4007. number of characters produced, excluding the null-terminator.
  4008. Unlike the C library 'asprintf', 'gmp_asprintf' doesn't return -1
  4009. if there's no more memory available, it lets the current allocation
  4010. function handle that.
  4011. -- Function: int gmp_obstack_printf (struct obstack *OB, const char
  4012. *FMT, ...)
  4013. -- Function: int gmp_obstack_vprintf (struct obstack *OB, const char
  4014. *FMT, va_list AP)
  4015. Append to the current object in OB. The return value is the number
  4016. of characters written. A null-terminator is not written.
  4017. FMT cannot be within the current object in OB, since that object
  4018. might move as it grows.
  4019. These functions are available only when the C library provides the
  4020. obstack feature, which probably means only on GNU systems, see
  4021. *note Obstacks: (libc)Obstacks.
  4022. 
  4023. File: gmp.info, Node: C++ Formatted Output, Prev: Formatted Output Functions, Up: Formatted Output
  4024. 10.3 C++ Formatted Output
  4025. =========================
  4026. The following functions are provided in 'libgmpxx' (*note Headers and
  4027. Libraries::), which is built if C++ support is enabled (*note Build
  4028. Options::). Prototypes are available from '<gmp.h>'.
  4029. -- Function: ostream& operator<< (ostream& STREAM, const mpz_t OP)
  4030. Print OP to STREAM, using its 'ios' formatting settings.
  4031. 'ios::width' is reset to 0 after output, the same as the standard
  4032. 'ostream operator<<' routines do.
  4033. In hex or octal, OP is printed as a signed number, the same as for
  4034. decimal. This is unlike the standard 'operator<<' routines on
  4035. 'int' etc, which instead give twos complement.
  4036. -- Function: ostream& operator<< (ostream& STREAM, const mpq_t OP)
  4037. Print OP to STREAM, using its 'ios' formatting settings.
  4038. 'ios::width' is reset to 0 after output, the same as the standard
  4039. 'ostream operator<<' routines do.
  4040. Output will be a fraction like '5/9', or if the denominator is 1
  4041. then just a plain integer like '123'.
  4042. In hex or octal, OP is printed as a signed value, the same as for
  4043. decimal. If 'ios::showbase' is set then a base indicator is shown
  4044. on both the numerator and denominator (if the denominator is
  4045. required).
  4046. -- Function: ostream& operator<< (ostream& STREAM, const mpf_t OP)
  4047. Print OP to STREAM, using its 'ios' formatting settings.
  4048. 'ios::width' is reset to 0 after output, the same as the standard
  4049. 'ostream operator<<' routines do.
  4050. The decimal point follows the standard library float 'operator<<',
  4051. which on recent systems means the 'std::locale' imbued on STREAM.
  4052. Hex and octal are supported, unlike the standard 'operator<<' on
  4053. 'double'. The mantissa will be in hex or octal, the exponent will
  4054. be in decimal. For hex the exponent delimiter is an '@'. This is
  4055. as per 'mpf_out_str'.
  4056. 'ios::showbase' is supported, and will put a base on the mantissa,
  4057. for example hex '0x1.8' or '0x0.8', or octal '01.4' or '00.4'.
  4058. This last form is slightly strange, but at least differentiates
  4059. itself from decimal.
  4060. These operators mean that GMP types can be printed in the usual C++
  4061. way, for example,
  4062. mpz_t z;
  4063. int n;
  4064. ...
  4065. cout << "iteration " << n << " value " << z << "\n";
  4066. But note that 'ostream' output (and 'istream' input, *note C++
  4067. Formatted Input::) is the only overloading available for the GMP types
  4068. and that for instance using '+' with an 'mpz_t' will have unpredictable
  4069. results. For classes with overloading, see *note C++ Class Interface::.
  4070. 
  4071. File: gmp.info, Node: Formatted Input, Next: C++ Class Interface, Prev: Formatted Output, Up: Top
  4072. 11 Formatted Input
  4073. ******************
  4074. * Menu:
  4075. * Formatted Input Strings::
  4076. * Formatted Input Functions::
  4077. * C++ Formatted Input::
  4078. 
  4079. File: gmp.info, Node: Formatted Input Strings, Next: Formatted Input Functions, Prev: Formatted Input, Up: Formatted Input
  4080. 11.1 Formatted Input Strings
  4081. ============================
  4082. 'gmp_scanf' and friends accept format strings similar to the standard C
  4083. 'scanf' (*note Formatted Input: (libc)Formatted Input.). A format
  4084. specification is of the form
  4085. % [flags] [width] [type] conv
  4086. GMP adds types 'Z', 'Q' and 'F' for 'mpz_t', 'mpq_t' and 'mpf_t'
  4087. respectively. 'Z' and 'Q' behave like integers. 'Q' will read a '/'
  4088. and a denominator, if present. 'F' behaves like a float.
  4089. GMP variables don't require an '&' when passed to 'gmp_scanf', since
  4090. they're already "call-by-reference". For example,
  4091. /* to read say "a(5) = 1234" */
  4092. int n;
  4093. mpz_t z;
  4094. gmp_scanf ("a(%d) = %Zd\n", &n, z);
  4095. mpq_t q1, q2;
  4096. gmp_sscanf ("0377 + 0x10/0x11", "%Qi + %Qi", q1, q2);
  4097. /* to read say "topleft (1.55,-2.66)" */
  4098. mpf_t x, y;
  4099. char buf[32];
  4100. gmp_scanf ("%31s (%Ff,%Ff)", buf, x, y);
  4101. All the standard C 'scanf' types behave the same as in the C library
  4102. 'scanf', and can be freely intermixed with the GMP extensions. In the
  4103. current implementation the standard parts of the format string are
  4104. simply handed to 'scanf' and only the GMP extensions handled directly.
  4105. The flags accepted are as follows. 'a' and ''' will depend on
  4106. support from the C library, and ''' cannot be used with GMP types.
  4107. * read but don't store
  4108. a allocate a buffer (string conversions)
  4109. ' grouped digits, GLIBC style (not GMP
  4110. types)
  4111. The standard types accepted are as follows. 'h' and 'l' are
  4112. portable, the rest will depend on the compiler (or include files) for
  4113. the type and the C library for the input.
  4114. h short
  4115. hh char
  4116. j intmax_t or uintmax_t
  4117. l long int, double or wchar_t
  4118. ll long long
  4119. L long double
  4120. q quad_t or u_quad_t
  4121. t ptrdiff_t
  4122. z size_t
  4123. The GMP types are
  4124. F mpf_t, float conversions
  4125. Q mpq_t, integer conversions
  4126. Z mpz_t, integer conversions
  4127. The conversions accepted are as follows. 'p' and '[' will depend on
  4128. support from the C library, the rest are standard.
  4129. c character or characters
  4130. d decimal integer
  4131. e E f g float
  4132. G
  4133. i integer with base indicator
  4134. n characters read so far
  4135. o octal integer
  4136. p pointer
  4137. s string of non-whitespace characters
  4138. u decimal integer
  4139. x X hex integer
  4140. [ string of characters in a set
  4141. 'e', 'E', 'f', 'g' and 'G' are identical, they all read either fixed
  4142. point or scientific format, and either upper or lower case 'e' for the
  4143. exponent in scientific format.
  4144. C99 style hex float format ('printf %a', *note Formatted Output
  4145. Strings::) is always accepted for 'mpf_t', but for the standard float
  4146. types it will depend on the C library.
  4147. 'x' and 'X' are identical, both accept both upper and lower case
  4148. hexadecimal.
  4149. 'o', 'u', 'x' and 'X' all read positive or negative values. For the
  4150. standard C types these are described as "unsigned" conversions, but that
  4151. merely affects certain overflow handling, negatives are still allowed
  4152. (per 'strtoul', *note Parsing of Integers: (libc)Parsing of Integers.).
  4153. For GMP types there are no overflows, so 'd' and 'u' are identical.
  4154. 'Q' type reads the numerator and (optional) denominator as given. If
  4155. the value might not be in canonical form then 'mpq_canonicalize' must be
  4156. called before using it in any calculations (*note Rational Number
  4157. Functions::).
  4158. 'Qi' will read a base specification separately for the numerator and
  4159. denominator. For example '0x10/11' would be 16/11, whereas '0x10/0x11'
  4160. would be 16/17.
  4161. 'n' can be used with any of the types above, even the GMP types. '*'
  4162. to suppress assignment is allowed, though in that case it would do
  4163. nothing at all.
  4164. Other conversions or types that might be accepted by the C library
  4165. 'scanf' cannot be used through 'gmp_scanf'.
  4166. Whitespace is read and discarded before a field, except for 'c' and
  4167. '[' conversions.
  4168. For float conversions, the decimal point character (or string)
  4169. expected is taken from the current locale settings on systems which
  4170. provide 'localeconv' (*note Locales and Internationalization:
  4171. (libc)Locales.). The C library will normally do the same for standard
  4172. float input.
  4173. The format string is only interpreted as plain 'char's, multibyte
  4174. characters are not recognised. Perhaps this will change in the future.
  4175. 
  4176. File: gmp.info, Node: Formatted Input Functions, Next: C++ Formatted Input, Prev: Formatted Input Strings, Up: Formatted Input
  4177. 11.2 Formatted Input Functions
  4178. ==============================
  4179. Each of the following functions is similar to the corresponding C
  4180. library function. The plain 'scanf' forms take a variable argument
  4181. list. The 'vscanf' forms take an argument pointer, see *note Variadic
  4182. Functions: (libc)Variadic Functions, or 'man 3 va_start'.
  4183. It should be emphasised that if a format string is invalid, or the
  4184. arguments don't match what the format specifies, then the behaviour of
  4185. any of these functions will be unpredictable. GCC format string
  4186. checking is not available, since it doesn't recognise the GMP
  4187. extensions.
  4188. No overlap is permitted between the FMT string and any of the results
  4189. produced.
  4190. -- Function: int gmp_scanf (const char *FMT, ...)
  4191. -- Function: int gmp_vscanf (const char *FMT, va_list AP)
  4192. Read from the standard input 'stdin'.
  4193. -- Function: int gmp_fscanf (FILE *FP, const char *FMT, ...)
  4194. -- Function: int gmp_vfscanf (FILE *FP, const char *FMT, va_list AP)
  4195. Read from the stream FP.
  4196. -- Function: int gmp_sscanf (const char *S, const char *FMT, ...)
  4197. -- Function: int gmp_vsscanf (const char *S, const char *FMT, va_list
  4198. AP)
  4199. Read from a null-terminated string S.
  4200. The return value from each of these functions is the same as the
  4201. standard C99 'scanf', namely the number of fields successfully parsed
  4202. and stored. '%n' fields and fields read but suppressed by '*' don't
  4203. count towards the return value.
  4204. If end of input (or a file error) is reached before a character for a
  4205. field or a literal, and if no previous non-suppressed fields have
  4206. matched, then the return value is 'EOF' instead of 0. A whitespace
  4207. character in the format string is only an optional match and doesn't
  4208. induce an 'EOF' in this fashion. Leading whitespace read and discarded
  4209. for a field don't count as characters for that field.
  4210. For the GMP types, input parsing follows C99 rules, namely one
  4211. character of lookahead is used and characters are read while they
  4212. continue to meet the format requirements. If this doesn't provide a
  4213. complete number then the function terminates, with that field not stored
  4214. nor counted towards the return value. For instance with 'mpf_t' an
  4215. input '1.23e-XYZ' would be read up to the 'X' and that character pushed
  4216. back since it's not a digit. The string '1.23e-' would then be
  4217. considered invalid since an 'e' must be followed by at least one digit.
  4218. For the standard C types, in the current implementation GMP calls the
  4219. C library 'scanf' functions, which might have looser rules about what
  4220. constitutes a valid input.
  4221. Note that 'gmp_sscanf' is the same as 'gmp_fscanf' and only does one
  4222. character of lookahead when parsing. Although clearly it could look at
  4223. its entire input, it is deliberately made identical to 'gmp_fscanf', the
  4224. same way C99 'sscanf' is the same as 'fscanf'.
  4225. 
  4226. File: gmp.info, Node: C++ Formatted Input, Prev: Formatted Input Functions, Up: Formatted Input
  4227. 11.3 C++ Formatted Input
  4228. ========================
  4229. The following functions are provided in 'libgmpxx' (*note Headers and
  4230. Libraries::), which is built only if C++ support is enabled (*note Build
  4231. Options::). Prototypes are available from '<gmp.h>'.
  4232. -- Function: istream& operator>> (istream& STREAM, mpz_t ROP)
  4233. Read ROP from STREAM, using its 'ios' formatting settings.
  4234. -- Function: istream& operator>> (istream& STREAM, mpq_t ROP)
  4235. An integer like '123' will be read, or a fraction like '5/9'. No
  4236. whitespace is allowed around the '/'. If the fraction is not in
  4237. canonical form then 'mpq_canonicalize' must be called (*note
  4238. Rational Number Functions::) before operating on it.
  4239. As per integer input, an '0' or '0x' base indicator is read when
  4240. none of 'ios::dec', 'ios::oct' or 'ios::hex' are set. This is done
  4241. separately for numerator and denominator, so that for instance
  4242. '0x10/11' is 16/11 and '0x10/0x11' is 16/17.
  4243. -- Function: istream& operator>> (istream& STREAM, mpf_t ROP)
  4244. Read ROP from STREAM, using its 'ios' formatting settings.
  4245. Hex or octal floats are not supported, but might be in the future,
  4246. or perhaps it's best to accept only what the standard float
  4247. 'operator>>' does.
  4248. Note that digit grouping specified by the 'istream' locale is
  4249. currently not accepted. Perhaps this will change in the future.
  4250. These operators mean that GMP types can be read in the usual C++ way,
  4251. for example,
  4252. mpz_t z;
  4253. ...
  4254. cin >> z;
  4255. But note that 'istream' input (and 'ostream' output, *note C++
  4256. Formatted Output::) is the only overloading available for the GMP types
  4257. and that for instance using '+' with an 'mpz_t' will have unpredictable
  4258. results. For classes with overloading, see *note C++ Class Interface::.
  4259. 
  4260. File: gmp.info, Node: C++ Class Interface, Next: Custom Allocation, Prev: Formatted Input, Up: Top
  4261. 12 C++ Class Interface
  4262. **********************
  4263. This chapter describes the C++ class based interface to GMP.
  4264. All GMP C language types and functions can be used in C++ programs,
  4265. since 'gmp.h' has 'extern "C"' qualifiers, but the class interface
  4266. offers overloaded functions and operators which may be more convenient.
  4267. Due to the implementation of this interface, a reasonably recent C++
  4268. compiler is required, one supporting namespaces, partial specialization
  4269. of templates and member templates.
  4270. *Everything described in this chapter is to be considered preliminary
  4271. and might be subject to incompatible changes if some unforeseen
  4272. difficulty reveals itself.*
  4273. * Menu:
  4274. * C++ Interface General::
  4275. * C++ Interface Integers::
  4276. * C++ Interface Rationals::
  4277. * C++ Interface Floats::
  4278. * C++ Interface Random Numbers::
  4279. * C++ Interface Limitations::
  4280. 
  4281. File: gmp.info, Node: C++ Interface General, Next: C++ Interface Integers, Prev: C++ Class Interface, Up: C++ Class Interface
  4282. 12.1 C++ Interface General
  4283. ==========================
  4284. All the C++ classes and functions are available with
  4285. #include <gmpxx.h>
  4286. Programs should be linked with the 'libgmpxx' and 'libgmp' libraries.
  4287. For example,
  4288. g++ mycxxprog.cc -lgmpxx -lgmp
  4289. The classes defined are
  4290. -- Class: mpz_class
  4291. -- Class: mpq_class
  4292. -- Class: mpf_class
  4293. The standard operators and various standard functions are overloaded
  4294. to allow arithmetic with these classes. For example,
  4295. int
  4296. main (void)
  4297. {
  4298. mpz_class a, b, c;
  4299. a = 1234;
  4300. b = "-5678";
  4301. c = a+b;
  4302. cout << "sum is " << c << "\n";
  4303. cout << "absolute value is " << abs(c) << "\n";
  4304. return 0;
  4305. }
  4306. An important feature of the implementation is that an expression like
  4307. 'a=b+c' results in a single call to the corresponding 'mpz_add', without
  4308. using a temporary for the 'b+c' part. Expressions which by their nature
  4309. imply intermediate values, like 'a=b*c+d*e', still use temporaries
  4310. though.
  4311. The classes can be freely intermixed in expressions, as can the
  4312. classes and the standard types 'long', 'unsigned long' and 'double'.
  4313. Smaller types like 'int' or 'float' can also be intermixed, since C++
  4314. will promote them.
  4315. Note that 'bool' is not accepted directly, but must be explicitly
  4316. cast to an 'int' first. This is because C++ will automatically convert
  4317. any pointer to a 'bool', so if GMP accepted 'bool' it would make all
  4318. sorts of invalid class and pointer combinations compile but almost
  4319. certainly not do anything sensible.
  4320. Conversions back from the classes to standard C++ types aren't done
  4321. automatically, instead member functions like 'get_si' are provided (see
  4322. the following sections for details).
  4323. Also there are no automatic conversions from the classes to the
  4324. corresponding GMP C types, instead a reference to the underlying C
  4325. object can be obtained with the following functions,
  4326. -- Function: mpz_t mpz_class::get_mpz_t ()
  4327. -- Function: mpq_t mpq_class::get_mpq_t ()
  4328. -- Function: mpf_t mpf_class::get_mpf_t ()
  4329. These can be used to call a C function which doesn't have a C++ class
  4330. interface. For example to set 'a' to the GCD of 'b' and 'c',
  4331. mpz_class a, b, c;
  4332. ...
  4333. mpz_gcd (a.get_mpz_t(), b.get_mpz_t(), c.get_mpz_t());
  4334. In the other direction, a class can be initialized from the
  4335. corresponding GMP C type, or assigned to if an explicit constructor is
  4336. used. In both cases this makes a copy of the value, it doesn't create
  4337. any sort of association. For example,
  4338. mpz_t z;
  4339. // ... init and calculate z ...
  4340. mpz_class x(z);
  4341. mpz_class y;
  4342. y = mpz_class (z);
  4343. There are no namespace setups in 'gmpxx.h', all types and functions
  4344. are simply put into the global namespace. This is what 'gmp.h' has done
  4345. in the past, and continues to do for compatibility. The extras provided
  4346. by 'gmpxx.h' follow GMP naming conventions and are unlikely to clash
  4347. with anything.
  4348. 
  4349. File: gmp.info, Node: C++ Interface Integers, Next: C++ Interface Rationals, Prev: C++ Interface General, Up: C++ Class Interface
  4350. 12.2 C++ Interface Integers
  4351. ===========================
  4352. -- Function: mpz_class::mpz_class (type N)
  4353. Construct an 'mpz_class'. All the standard C++ types may be used,
  4354. except 'long long' and 'long double', and all the GMP C++ classes
  4355. can be used, although conversions from 'mpq_class' and 'mpf_class'
  4356. are 'explicit'. Any necessary conversion follows the corresponding
  4357. C function, for example 'double' follows 'mpz_set_d' (*note
  4358. Assigning Integers::).
  4359. -- Function: explicit mpz_class::mpz_class (const mpz_t Z)
  4360. Construct an 'mpz_class' from an 'mpz_t'. The value in Z is copied
  4361. into the new 'mpz_class', there won't be any permanent association
  4362. between it and Z.
  4363. -- Function: explicit mpz_class::mpz_class (const char *S, int BASE =
  4364. 0)
  4365. -- Function: explicit mpz_class::mpz_class (const string& S, int BASE =
  4366. 0)
  4367. Construct an 'mpz_class' converted from a string using
  4368. 'mpz_set_str' (*note Assigning Integers::).
  4369. If the string is not a valid integer, an 'std::invalid_argument'
  4370. exception is thrown. The same applies to 'operator='.
  4371. -- Function: mpz_class operator"" _mpz (const char *STR)
  4372. With C++11 compilers, integers can be constructed with the syntax
  4373. '123_mpz' which is equivalent to 'mpz_class("123")'.
  4374. -- Function: mpz_class operator/ (mpz_class A, mpz_class D)
  4375. -- Function: mpz_class operator% (mpz_class A, mpz_class D)
  4376. Divisions involving 'mpz_class' round towards zero, as per the
  4377. 'mpz_tdiv_q' and 'mpz_tdiv_r' functions (*note Integer Division::).
  4378. This is the same as the C99 '/' and '%' operators.
  4379. The 'mpz_fdiv...' or 'mpz_cdiv...' functions can always be called
  4380. directly if desired. For example,
  4381. mpz_class q, a, d;
  4382. ...
  4383. mpz_fdiv_q (q.get_mpz_t(), a.get_mpz_t(), d.get_mpz_t());
  4384. -- Function: mpz_class abs (mpz_class OP)
  4385. -- Function: int cmp (mpz_class OP1, type OP2)
  4386. -- Function: int cmp (type OP1, mpz_class OP2)
  4387. -- Function: bool mpz_class::fits_sint_p (void)
  4388. -- Function: bool mpz_class::fits_slong_p (void)
  4389. -- Function: bool mpz_class::fits_sshort_p (void)
  4390. -- Function: bool mpz_class::fits_uint_p (void)
  4391. -- Function: bool mpz_class::fits_ulong_p (void)
  4392. -- Function: bool mpz_class::fits_ushort_p (void)
  4393. -- Function: double mpz_class::get_d (void)
  4394. -- Function: long mpz_class::get_si (void)
  4395. -- Function: string mpz_class::get_str (int BASE = 10)
  4396. -- Function: unsigned long mpz_class::get_ui (void)
  4397. -- Function: int mpz_class::set_str (const char *STR, int BASE)
  4398. -- Function: int mpz_class::set_str (const string& STR, int BASE)
  4399. -- Function: int sgn (mpz_class OP)
  4400. -- Function: mpz_class sqrt (mpz_class OP)
  4401. -- Function: mpz_class gcd (mpz_class OP1, mpz_class OP2)
  4402. -- Function: mpz_class lcm (mpz_class OP1, mpz_class OP2)
  4403. -- Function: void mpz_class::swap (mpz_class& OP)
  4404. -- Function: void swap (mpz_class& OP1, mpz_class& OP2)
  4405. These functions provide a C++ class interface to the corresponding
  4406. GMP C routines.
  4407. 'cmp' can be used with any of the classes or the standard C++
  4408. types, except 'long long' and 'long double'.
  4409. Overloaded operators for combinations of 'mpz_class' and 'double' are
  4410. provided for completeness, but it should be noted that if the given
  4411. 'double' is not an integer then the way any rounding is done is
  4412. currently unspecified. The rounding might take place at the start, in
  4413. the middle, or at the end of the operation, and it might change in the
  4414. future.
  4415. Conversions between 'mpz_class' and 'double', however, are defined to
  4416. follow the corresponding C functions 'mpz_get_d' and 'mpz_set_d'. And
  4417. comparisons are always made exactly, as per 'mpz_cmp_d'.
  4418. 
  4419. File: gmp.info, Node: C++ Interface Rationals, Next: C++ Interface Floats, Prev: C++ Interface Integers, Up: C++ Class Interface
  4420. 12.3 C++ Interface Rationals
  4421. ============================
  4422. In all the following constructors, if a fraction is given then it should
  4423. be in canonical form, or if not then 'mpq_class::canonicalize' called.
  4424. -- Function: mpq_class::mpq_class (type OP)
  4425. -- Function: mpq_class::mpq_class (integer NUM, integer DEN)
  4426. Construct an 'mpq_class'. The initial value can be a single value
  4427. of any type (conversion from 'mpf_class' is 'explicit'), or a pair
  4428. of integers ('mpz_class' or standard C++ integer types)
  4429. representing a fraction, except that 'long long' and 'long double'
  4430. are not supported. For example,
  4431. mpq_class q (99);
  4432. mpq_class q (1.75);
  4433. mpq_class q (1, 3);
  4434. -- Function: explicit mpq_class::mpq_class (const mpq_t Q)
  4435. Construct an 'mpq_class' from an 'mpq_t'. The value in Q is copied
  4436. into the new 'mpq_class', there won't be any permanent association
  4437. between it and Q.
  4438. -- Function: explicit mpq_class::mpq_class (const char *S, int BASE =
  4439. 0)
  4440. -- Function: explicit mpq_class::mpq_class (const string& S, int BASE =
  4441. 0)
  4442. Construct an 'mpq_class' converted from a string using
  4443. 'mpq_set_str' (*note Initializing Rationals::).
  4444. If the string is not a valid rational, an 'std::invalid_argument'
  4445. exception is thrown. The same applies to 'operator='.
  4446. -- Function: mpq_class operator"" _mpq (const char *STR)
  4447. With C++11 compilers, integral rationals can be constructed with
  4448. the syntax '123_mpq' which is equivalent to 'mpq_class(123_mpz)'.
  4449. Other rationals can be built as '-1_mpq/2' or '0xb_mpq/123456_mpz'.
  4450. -- Function: void mpq_class::canonicalize ()
  4451. Put an 'mpq_class' into canonical form, as per *note Rational
  4452. Number Functions::. All arithmetic operators require their
  4453. operands in canonical form, and will return results in canonical
  4454. form.
  4455. -- Function: mpq_class abs (mpq_class OP)
  4456. -- Function: int cmp (mpq_class OP1, type OP2)
  4457. -- Function: int cmp (type OP1, mpq_class OP2)
  4458. -- Function: double mpq_class::get_d (void)
  4459. -- Function: string mpq_class::get_str (int BASE = 10)
  4460. -- Function: int mpq_class::set_str (const char *STR, int BASE)
  4461. -- Function: int mpq_class::set_str (const string& STR, int BASE)
  4462. -- Function: int sgn (mpq_class OP)
  4463. -- Function: void mpq_class::swap (mpq_class& OP)
  4464. -- Function: void swap (mpq_class& OP1, mpq_class& OP2)
  4465. These functions provide a C++ class interface to the corresponding
  4466. GMP C routines.
  4467. 'cmp' can be used with any of the classes or the standard C++
  4468. types, except 'long long' and 'long double'.
  4469. -- Function: mpz_class& mpq_class::get_num ()
  4470. -- Function: mpz_class& mpq_class::get_den ()
  4471. Get a reference to an 'mpz_class' which is the numerator or
  4472. denominator of an 'mpq_class'. This can be used both for read and
  4473. write access. If the object returned is modified, it modifies the
  4474. original 'mpq_class'.
  4475. If direct manipulation might produce a non-canonical value, then
  4476. 'mpq_class::canonicalize' must be called before further operations.
  4477. -- Function: mpz_t mpq_class::get_num_mpz_t ()
  4478. -- Function: mpz_t mpq_class::get_den_mpz_t ()
  4479. Get a reference to the underlying 'mpz_t' numerator or denominator
  4480. of an 'mpq_class'. This can be passed to C functions expecting an
  4481. 'mpz_t'. Any modifications made to the 'mpz_t' will modify the
  4482. original 'mpq_class'.
  4483. If direct manipulation might produce a non-canonical value, then
  4484. 'mpq_class::canonicalize' must be called before further operations.
  4485. -- Function: istream& operator>> (istream& STREAM, mpq_class& ROP);
  4486. Read ROP from STREAM, using its 'ios' formatting settings, the same
  4487. as 'mpq_t operator>>' (*note C++ Formatted Input::).
  4488. If the ROP read might not be in canonical form then
  4489. 'mpq_class::canonicalize' must be called.
  4490. 
  4491. File: gmp.info, Node: C++ Interface Floats, Next: C++ Interface Random Numbers, Prev: C++ Interface Rationals, Up: C++ Class Interface
  4492. 12.4 C++ Interface Floats
  4493. =========================
  4494. When an expression requires the use of temporary intermediate
  4495. 'mpf_class' values, like 'f=g*h+x*y', those temporaries will have the
  4496. same precision as the destination 'f'. Explicit constructors can be
  4497. used if this doesn't suit.
  4498. -- Function: mpf_class::mpf_class (type OP)
  4499. -- Function: mpf_class::mpf_class (type OP, mp_bitcnt_t PREC)
  4500. Construct an 'mpf_class'. Any standard C++ type can be used,
  4501. except 'long long' and 'long double', and any of the GMP C++
  4502. classes can be used.
  4503. If PREC is given, the initial precision is that value, in bits. If
  4504. PREC is not given, then the initial precision is determined by the
  4505. type of OP given. An 'mpz_class', 'mpq_class', or C++ builtin type
  4506. will give the default 'mpf' precision (*note Initializing
  4507. Floats::). An 'mpf_class' or expression will give the precision of
  4508. that value. The precision of a binary expression is the higher of
  4509. the two operands.
  4510. mpf_class f(1.5); // default precision
  4511. mpf_class f(1.5, 500); // 500 bits (at least)
  4512. mpf_class f(x); // precision of x
  4513. mpf_class f(abs(x)); // precision of x
  4514. mpf_class f(-g, 1000); // 1000 bits (at least)
  4515. mpf_class f(x+y); // greater of precisions of x and y
  4516. -- Function: explicit mpf_class::mpf_class (const mpf_t F)
  4517. -- Function: mpf_class::mpf_class (const mpf_t F, mp_bitcnt_t PREC)
  4518. Construct an 'mpf_class' from an 'mpf_t'. The value in F is copied
  4519. into the new 'mpf_class', there won't be any permanent association
  4520. between it and F.
  4521. If PREC is given, the initial precision is that value, in bits. If
  4522. PREC is not given, then the initial precision is that of F.
  4523. -- Function: explicit mpf_class::mpf_class (const char *S)
  4524. -- Function: mpf_class::mpf_class (const char *S, mp_bitcnt_t PREC, int
  4525. BASE = 0)
  4526. -- Function: explicit mpf_class::mpf_class (const string& S)
  4527. -- Function: mpf_class::mpf_class (const string& S, mp_bitcnt_t PREC,
  4528. int BASE = 0)
  4529. Construct an 'mpf_class' converted from a string using
  4530. 'mpf_set_str' (*note Assigning Floats::). If PREC is given, the
  4531. initial precision is that value, in bits. If not, the default
  4532. 'mpf' precision (*note Initializing Floats::) is used.
  4533. If the string is not a valid float, an 'std::invalid_argument'
  4534. exception is thrown. The same applies to 'operator='.
  4535. -- Function: mpf_class operator"" _mpf (const char *STR)
  4536. With C++11 compilers, floats can be constructed with the syntax
  4537. '1.23e-1_mpf' which is equivalent to 'mpf_class("1.23e-1")'.
  4538. -- Function: mpf_class& mpf_class::operator= (type OP)
  4539. Convert and store the given OP value to an 'mpf_class' object. The
  4540. same types are accepted as for the constructors above.
  4541. Note that 'operator=' only stores a new value, it doesn't copy or
  4542. change the precision of the destination, instead the value is
  4543. truncated if necessary. This is the same as 'mpf_set' etc. Note
  4544. in particular this means for 'mpf_class' a copy constructor is not
  4545. the same as a default constructor plus assignment.
  4546. mpf_class x (y); // x created with precision of y
  4547. mpf_class x; // x created with default precision
  4548. x = y; // value truncated to that precision
  4549. Applications using templated code may need to be careful about the
  4550. assumptions the code makes in this area, when working with
  4551. 'mpf_class' values of various different or non-default precisions.
  4552. For instance implementations of the standard 'complex' template
  4553. have been seen in both styles above, though of course 'complex' is
  4554. normally only actually specified for use with the builtin float
  4555. types.
  4556. -- Function: mpf_class abs (mpf_class OP)
  4557. -- Function: mpf_class ceil (mpf_class OP)
  4558. -- Function: int cmp (mpf_class OP1, type OP2)
  4559. -- Function: int cmp (type OP1, mpf_class OP2)
  4560. -- Function: bool mpf_class::fits_sint_p (void)
  4561. -- Function: bool mpf_class::fits_slong_p (void)
  4562. -- Function: bool mpf_class::fits_sshort_p (void)
  4563. -- Function: bool mpf_class::fits_uint_p (void)
  4564. -- Function: bool mpf_class::fits_ulong_p (void)
  4565. -- Function: bool mpf_class::fits_ushort_p (void)
  4566. -- Function: mpf_class floor (mpf_class OP)
  4567. -- Function: mpf_class hypot (mpf_class OP1, mpf_class OP2)
  4568. -- Function: double mpf_class::get_d (void)
  4569. -- Function: long mpf_class::get_si (void)
  4570. -- Function: string mpf_class::get_str (mp_exp_t& EXP, int BASE = 10,
  4571. size_t DIGITS = 0)
  4572. -- Function: unsigned long mpf_class::get_ui (void)
  4573. -- Function: int mpf_class::set_str (const char *STR, int BASE)
  4574. -- Function: int mpf_class::set_str (const string& STR, int BASE)
  4575. -- Function: int sgn (mpf_class OP)
  4576. -- Function: mpf_class sqrt (mpf_class OP)
  4577. -- Function: void mpf_class::swap (mpf_class& OP)
  4578. -- Function: void swap (mpf_class& OP1, mpf_class& OP2)
  4579. -- Function: mpf_class trunc (mpf_class OP)
  4580. These functions provide a C++ class interface to the corresponding
  4581. GMP C routines.
  4582. 'cmp' can be used with any of the classes or the standard C++
  4583. types, except 'long long' and 'long double'.
  4584. The accuracy provided by 'hypot' is not currently guaranteed.
  4585. -- Function: mp_bitcnt_t mpf_class::get_prec ()
  4586. -- Function: void mpf_class::set_prec (mp_bitcnt_t PREC)
  4587. -- Function: void mpf_class::set_prec_raw (mp_bitcnt_t PREC)
  4588. Get or set the current precision of an 'mpf_class'.
  4589. The restrictions described for 'mpf_set_prec_raw' (*note
  4590. Initializing Floats::) apply to 'mpf_class::set_prec_raw'. Note in
  4591. particular that the 'mpf_class' must be restored to it's allocated
  4592. precision before being destroyed. This must be done by application
  4593. code, there's no automatic mechanism for it.
  4594. 
  4595. File: gmp.info, Node: C++ Interface Random Numbers, Next: C++ Interface Limitations, Prev: C++ Interface Floats, Up: C++ Class Interface
  4596. 12.5 C++ Interface Random Numbers
  4597. =================================
  4598. -- Class: gmp_randclass
  4599. The C++ class interface to the GMP random number functions uses
  4600. 'gmp_randclass' to hold an algorithm selection and current state,
  4601. as per 'gmp_randstate_t'.
  4602. -- Function: gmp_randclass::gmp_randclass (void (*RANDINIT)
  4603. (gmp_randstate_t, ...), ...)
  4604. Construct a 'gmp_randclass', using a call to the given RANDINIT
  4605. function (*note Random State Initialization::). The arguments
  4606. expected are the same as RANDINIT, but with 'mpz_class' instead of
  4607. 'mpz_t'. For example,
  4608. gmp_randclass r1 (gmp_randinit_default);
  4609. gmp_randclass r2 (gmp_randinit_lc_2exp_size, 32);
  4610. gmp_randclass r3 (gmp_randinit_lc_2exp, a, c, m2exp);
  4611. gmp_randclass r4 (gmp_randinit_mt);
  4612. 'gmp_randinit_lc_2exp_size' will fail if the size requested is too
  4613. big, an 'std::length_error' exception is thrown in that case.
  4614. -- Function: gmp_randclass::gmp_randclass (gmp_randalg_t ALG, ...)
  4615. Construct a 'gmp_randclass' using the same parameters as
  4616. 'gmp_randinit' (*note Random State Initialization::). This
  4617. function is obsolete and the above RANDINIT style should be
  4618. preferred.
  4619. -- Function: void gmp_randclass::seed (unsigned long int S)
  4620. -- Function: void gmp_randclass::seed (mpz_class S)
  4621. Seed a random number generator. See *note Random Number
  4622. Functions::, for how to choose a good seed.
  4623. -- Function: mpz_class gmp_randclass::get_z_bits (mp_bitcnt_t BITS)
  4624. -- Function: mpz_class gmp_randclass::get_z_bits (mpz_class BITS)
  4625. Generate a random integer with a specified number of bits.
  4626. -- Function: mpz_class gmp_randclass::get_z_range (mpz_class N)
  4627. Generate a random integer in the range 0 to N-1 inclusive.
  4628. -- Function: mpf_class gmp_randclass::get_f ()
  4629. -- Function: mpf_class gmp_randclass::get_f (mp_bitcnt_t PREC)
  4630. Generate a random float F in the range 0 <= F < 1. F will be to
  4631. PREC bits precision, or if PREC is not given then to the precision
  4632. of the destination. For example,
  4633. gmp_randclass r;
  4634. ...
  4635. mpf_class f (0, 512); // 512 bits precision
  4636. f = r.get_f(); // random number, 512 bits
  4637. 
  4638. File: gmp.info, Node: C++ Interface Limitations, Prev: C++ Interface Random Numbers, Up: C++ Class Interface
  4639. 12.6 C++ Interface Limitations
  4640. ==============================
  4641. 'mpq_class' and Templated Reading
  4642. A generic piece of template code probably won't know that
  4643. 'mpq_class' requires a 'canonicalize' call if inputs read with
  4644. 'operator>>' might be non-canonical. This can lead to incorrect
  4645. results.
  4646. 'operator>>' behaves as it does for reasons of efficiency. A
  4647. canonicalize can be quite time consuming on large operands, and is
  4648. best avoided if it's not necessary.
  4649. But this potential difficulty reduces the usefulness of
  4650. 'mpq_class'. Perhaps a mechanism to tell 'operator>>' what to do
  4651. will be adopted in the future, maybe a preprocessor define, a
  4652. global flag, or an 'ios' flag pressed into service. Or maybe, at
  4653. the risk of inconsistency, the 'mpq_class' 'operator>>' could
  4654. canonicalize and leave 'mpq_t' 'operator>>' not doing so, for use
  4655. on those occasions when that's acceptable. Send feedback or
  4656. alternate ideas to <gmp-bugs@gmplib.org>.
  4657. Subclassing
  4658. Subclassing the GMP C++ classes works, but is not currently
  4659. recommended.
  4660. Expressions involving subclasses resolve correctly (or seem to),
  4661. but in normal C++ fashion the subclass doesn't inherit constructors
  4662. and assignments. There's many of those in the GMP classes, and a
  4663. good way to reestablish them in a subclass is not yet provided.
  4664. Templated Expressions
  4665. A subtle difficulty exists when using expressions together with
  4666. application-defined template functions. Consider the following,
  4667. with 'T' intended to be some numeric type,
  4668. template <class T>
  4669. T fun (const T &, const T &);
  4670. When used with, say, plain 'mpz_class' variables, it works fine:
  4671. 'T' is resolved as 'mpz_class'.
  4672. mpz_class f(1), g(2);
  4673. fun (f, g); // Good
  4674. But when one of the arguments is an expression, it doesn't work.
  4675. mpz_class f(1), g(2), h(3);
  4676. fun (f, g+h); // Bad
  4677. This is because 'g+h' ends up being a certain expression template
  4678. type internal to 'gmpxx.h', which the C++ template resolution rules
  4679. are unable to automatically convert to 'mpz_class'. The workaround
  4680. is simply to add an explicit cast.
  4681. mpz_class f(1), g(2), h(3);
  4682. fun (f, mpz_class(g+h)); // Good
  4683. Similarly, within 'fun' it may be necessary to cast an expression
  4684. to type 'T' when calling a templated 'fun2'.
  4685. template <class T>
  4686. void fun (T f, T g)
  4687. {
  4688. fun2 (f, f+g); // Bad
  4689. }
  4690. template <class T>
  4691. void fun (T f, T g)
  4692. {
  4693. fun2 (f, T(f+g)); // Good
  4694. }
  4695. C++11
  4696. C++11 provides several new ways in which types can be inferred:
  4697. 'auto', 'decltype', etc. While they can be very convenient, they
  4698. don't mix well with expression templates. In this example, the
  4699. addition is performed twice, as if we had defined 'sum' as a macro.
  4700. mpz_class z = 33;
  4701. auto sum = z + z;
  4702. mpz_class prod = sum * sum;
  4703. This other example may crash, though some compilers might make it
  4704. look like it is working, because the expression 'z+z' goes out of
  4705. scope before it is evaluated.
  4706. mpz_class z = 33;
  4707. auto sum = z + z + z;
  4708. mpz_class prod = sum * 2;
  4709. It is thus strongly recommended to avoid 'auto' anywhere a GMP C++
  4710. expression may appear.
  4711. 
  4712. File: gmp.info, Node: Custom Allocation, Next: Language Bindings, Prev: C++ Class Interface, Up: Top
  4713. 13 Custom Allocation
  4714. ********************
  4715. By default GMP uses 'malloc', 'realloc' and 'free' for memory
  4716. allocation, and if they fail GMP prints a message to the standard error
  4717. output and terminates the program.
  4718. Alternate functions can be specified, to allocate memory in a
  4719. different way or to have a different error action on running out of
  4720. memory.
  4721. -- Function: void mp_set_memory_functions (
  4722. void *(*ALLOC_FUNC_PTR) (size_t),
  4723. void *(*REALLOC_FUNC_PTR) (void *, size_t, size_t),
  4724. void (*FREE_FUNC_PTR) (void *, size_t))
  4725. Replace the current allocation functions from the arguments. If an
  4726. argument is 'NULL', the corresponding default function is used.
  4727. These functions will be used for all memory allocation done by GMP,
  4728. apart from temporary space from 'alloca' if that function is
  4729. available and GMP is configured to use it (*note Build Options::).
  4730. *Be sure to call 'mp_set_memory_functions' only when there are no
  4731. active GMP objects allocated using the previous memory functions!
  4732. Usually that means calling it before any other GMP function.*
  4733. The functions supplied should fit the following declarations:
  4734. -- Function: void * allocate_function (size_t ALLOC_SIZE)
  4735. Return a pointer to newly allocated space with at least ALLOC_SIZE
  4736. bytes.
  4737. -- Function: void * reallocate_function (void *PTR, size_t OLD_SIZE,
  4738. size_t NEW_SIZE)
  4739. Resize a previously allocated block PTR of OLD_SIZE bytes to be
  4740. NEW_SIZE bytes.
  4741. The block may be moved if necessary or if desired, and in that case
  4742. the smaller of OLD_SIZE and NEW_SIZE bytes must be copied to the
  4743. new location. The return value is a pointer to the resized block,
  4744. that being the new location if moved or just PTR if not.
  4745. PTR is never 'NULL', it's always a previously allocated block.
  4746. NEW_SIZE may be bigger or smaller than OLD_SIZE.
  4747. -- Function: void free_function (void *PTR, size_t SIZE)
  4748. De-allocate the space pointed to by PTR.
  4749. PTR is never 'NULL', it's always a previously allocated block of
  4750. SIZE bytes.
  4751. A "byte" here means the unit used by the 'sizeof' operator.
  4752. The REALLOCATE_FUNCTION parameter OLD_SIZE and the FREE_FUNCTION
  4753. parameter SIZE are passed for convenience, but of course they can be
  4754. ignored if not needed by an implementation. The default functions using
  4755. 'malloc' and friends for instance don't use them.
  4756. No error return is allowed from any of these functions, if they
  4757. return then they must have performed the specified operation. In
  4758. particular note that ALLOCATE_FUNCTION or REALLOCATE_FUNCTION mustn't
  4759. return 'NULL'.
  4760. Getting a different fatal error action is a good use for custom
  4761. allocation functions, for example giving a graphical dialog rather than
  4762. the default print to 'stderr'. How much is possible when genuinely out
  4763. of memory is another question though.
  4764. There's currently no defined way for the allocation functions to
  4765. recover from an error such as out of memory, they must terminate program
  4766. execution. A 'longjmp' or throwing a C++ exception will have undefined
  4767. results. This may change in the future.
  4768. GMP may use allocated blocks to hold pointers to other allocated
  4769. blocks. This will limit the assumptions a conservative garbage
  4770. collection scheme can make.
  4771. Since the default GMP allocation uses 'malloc' and friends, those
  4772. functions will be linked in even if the first thing a program does is an
  4773. 'mp_set_memory_functions'. It's necessary to change the GMP sources if
  4774. this is a problem.
  4775. -- Function: void mp_get_memory_functions (
  4776. void *(**ALLOC_FUNC_PTR) (size_t),
  4777. void *(**REALLOC_FUNC_PTR) (void *, size_t, size_t),
  4778. void (**FREE_FUNC_PTR) (void *, size_t))
  4779. Get the current allocation functions, storing function pointers to
  4780. the locations given by the arguments. If an argument is 'NULL',
  4781. that function pointer is not stored.
  4782. For example, to get just the current free function,
  4783. void (*freefunc) (void *, size_t);
  4784. mp_get_memory_functions (NULL, NULL, &freefunc);
  4785. 
  4786. File: gmp.info, Node: Language Bindings, Next: Algorithms, Prev: Custom Allocation, Up: Top
  4787. 14 Language Bindings
  4788. ********************
  4789. The following packages and projects offer access to GMP from languages
  4790. other than C, though perhaps with varying levels of functionality and
  4791. efficiency.
  4792. C++
  4793. * GMP C++ class interface, *note C++ Class Interface::
  4794. Straightforward interface, expression templates to eliminate
  4795. temporaries.
  4796. * ALP <https://www-sop.inria.fr/saga/logiciels/ALP/>
  4797. Linear algebra and polynomials using templates.
  4798. * Arithmos <http://cant.ua.ac.be/old/arithmos/>
  4799. Rationals with infinities and square roots.
  4800. * CLN <http://www.ginac.de/CLN/>
  4801. High level classes for arithmetic.
  4802. * Linbox <http://www.linalg.org/>
  4803. Sparse vectors and matrices.
  4804. * NTL <http://www.shoup.net/ntl/>
  4805. A C++ number theory library.
  4806. Eiffel
  4807. * Eiffelroom <http://www.eiffelroom.org/node/442>
  4808. Haskell
  4809. * Glasgow Haskell Compiler <https://www.haskell.org/ghc/>
  4810. Java
  4811. * Kaffe <https://github.com/kaffe/kaffe>
  4812. Lisp
  4813. * GNU Common Lisp <https://www.gnu.org/software/gcl/gcl.html>
  4814. * Librep <http://librep.sourceforge.net/>
  4815. * XEmacs (21.5.18 beta and up) <http://www.xemacs.org>
  4816. Optional big integers, rationals and floats using GMP.
  4817. M4
  4818. * GNU m4 betas <http://www.seindal.dk/rene/gnu/>
  4819. Optionally provides an arbitrary precision 'mpeval'.
  4820. ML
  4821. * MLton compiler <http://mlton.org/>
  4822. Objective Caml
  4823. * MLGMP <http://opam.ocamlpro.com/pkg/mlgmp.20120224.html>
  4824. * Numerix <http://pauillac.inria.fr/~quercia/>
  4825. Optionally using GMP.
  4826. Oz
  4827. * Mozart <http://mozart.github.io/>
  4828. Pascal
  4829. * GNU Pascal Compiler <http://www.gnu-pascal.de/>
  4830. GMP unit.
  4831. * Numerix <http://pauillac.inria.fr/~quercia/>
  4832. For Free Pascal, optionally using GMP.
  4833. Perl
  4834. * GMP module, see 'demos/perl' in the GMP sources (*note
  4835. Demonstration Programs::).
  4836. * Math::GMP <http://www.cpan.org/>
  4837. Compatible with Math::BigInt, but not as many functions as the
  4838. GMP module above.
  4839. * Math::BigInt::GMP <http://www.cpan.org/>
  4840. Plug Math::GMP into normal Math::BigInt operations.
  4841. Pike
  4842. * mpz module in the standard distribution,
  4843. <http://pike.ida.liu.se/>
  4844. Prolog
  4845. * SWI Prolog <http://www.swi-prolog.org/>
  4846. Arbitrary precision floats.
  4847. Python
  4848. * GMPY <https://code.google.com/p/gmpy/>
  4849. Ruby
  4850. * http://rubygems.org/gems/gmp
  4851. Scheme
  4852. * GNU Guile <https://www.gnu.org/software/guile/guile.html>
  4853. * RScheme <http://www.rscheme.org/>
  4854. * STklos <http://www.stklos.net/>
  4855. Smalltalk
  4856. * GNU Smalltalk
  4857. <http://www.smalltalk.org/versions/GNUSmalltalk.html>
  4858. Other
  4859. * Axiom <https://savannah.nongnu.org/projects/axiom>
  4860. Computer algebra using GCL.
  4861. * DrGenius <http://drgenius.seul.org/>
  4862. Geometry system and mathematical programming language.
  4863. * GiNaC <http://www.ginac.de/>
  4864. C++ computer algebra using CLN.
  4865. * GOO <https://www.eecs.berkeley.edu/~jrb/goo/>
  4866. Dynamic object oriented language.
  4867. * Maxima <https://www.ma.utexas.edu/users/wfs/maxima.html>
  4868. Macsyma computer algebra using GCL.
  4869. * Regina <http://regina.sourceforge.net/>
  4870. Topological calculator.
  4871. * Yacas <http://yacas.sourceforge.net>
  4872. Yet another computer algebra system.
  4873. 
  4874. File: gmp.info, Node: Algorithms, Next: Internals, Prev: Language Bindings, Up: Top
  4875. 15 Algorithms
  4876. *************
  4877. This chapter is an introduction to some of the algorithms used for
  4878. various GMP operations. The code is likely to be hard to understand
  4879. without knowing something about the algorithms.
  4880. Some GMP internals are mentioned, but applications that expect to be
  4881. compatible with future GMP releases should take care to use only the
  4882. documented functions.
  4883. * Menu:
  4884. * Multiplication Algorithms::
  4885. * Division Algorithms::
  4886. * Greatest Common Divisor Algorithms::
  4887. * Powering Algorithms::
  4888. * Root Extraction Algorithms::
  4889. * Radix Conversion Algorithms::
  4890. * Other Algorithms::
  4891. * Assembly Coding::
  4892. 
  4893. File: gmp.info, Node: Multiplication Algorithms, Next: Division Algorithms, Prev: Algorithms, Up: Algorithms
  4894. 15.1 Multiplication
  4895. ===================
  4896. NxN limb multiplications and squares are done using one of seven
  4897. algorithms, as the size N increases.
  4898. Algorithm Threshold
  4899. Basecase (none)
  4900. Karatsuba 'MUL_TOOM22_THRESHOLD'
  4901. Toom-3 'MUL_TOOM33_THRESHOLD'
  4902. Toom-4 'MUL_TOOM44_THRESHOLD'
  4903. Toom-6.5 'MUL_TOOM6H_THRESHOLD'
  4904. Toom-8.5 'MUL_TOOM8H_THRESHOLD'
  4905. FFT 'MUL_FFT_THRESHOLD'
  4906. Similarly for squaring, with the 'SQR' thresholds.
  4907. NxM multiplications of operands with different sizes above
  4908. 'MUL_TOOM22_THRESHOLD' are currently done by special Toom-inspired
  4909. algorithms or directly with FFT, depending on operand size (*note
  4910. Unbalanced Multiplication::).
  4911. * Menu:
  4912. * Basecase Multiplication::
  4913. * Karatsuba Multiplication::
  4914. * Toom 3-Way Multiplication::
  4915. * Toom 4-Way Multiplication::
  4916. * Higher degree Toom'n'half::
  4917. * FFT Multiplication::
  4918. * Other Multiplication::
  4919. * Unbalanced Multiplication::
  4920. 
  4921. File: gmp.info, Node: Basecase Multiplication, Next: Karatsuba Multiplication, Prev: Multiplication Algorithms, Up: Multiplication Algorithms
  4922. 15.1.1 Basecase Multiplication
  4923. ------------------------------
  4924. Basecase NxM multiplication is a straightforward rectangular set of
  4925. cross-products, the same as long multiplication done by hand and for
  4926. that reason sometimes known as the schoolbook or grammar school method.
  4927. This is an O(N*M) algorithm. See Knuth section 4.3.1 algorithm M (*note
  4928. References::), and the 'mpn/generic/mul_basecase.c' code.
  4929. Assembly implementations of 'mpn_mul_basecase' are essentially the
  4930. same as the generic C code, but have all the usual assembly tricks and
  4931. obscurities introduced for speed.
  4932. A square can be done in roughly half the time of a multiply, by using
  4933. the fact that the cross products above and below the diagonal are the
  4934. same. A triangle of products below the diagonal is formed, doubled
  4935. (left shift by one bit), and then the products on the diagonal added.
  4936. This can be seen in 'mpn/generic/sqr_basecase.c'. Again the assembly
  4937. implementations take essentially the same approach.
  4938. u0 u1 u2 u3 u4
  4939. +---+---+---+---+---+
  4940. u0 | d | | | | |
  4941. +---+---+---+---+---+
  4942. u1 | | d | | | |
  4943. +---+---+---+---+---+
  4944. u2 | | | d | | |
  4945. +---+---+---+---+---+
  4946. u3 | | | | d | |
  4947. +---+---+---+---+---+
  4948. u4 | | | | | d |
  4949. +---+---+---+---+---+
  4950. In practice squaring isn't a full 2x faster than multiplying, it's
  4951. usually around 1.5x. Less than 1.5x probably indicates
  4952. 'mpn_sqr_basecase' wants improving on that CPU.
  4953. On some CPUs 'mpn_mul_basecase' can be faster than the generic C
  4954. 'mpn_sqr_basecase' on some small sizes. 'SQR_BASECASE_THRESHOLD' is the
  4955. size at which to use 'mpn_sqr_basecase', this will be zero if that
  4956. routine should be used always.
  4957. 
  4958. File: gmp.info, Node: Karatsuba Multiplication, Next: Toom 3-Way Multiplication, Prev: Basecase Multiplication, Up: Multiplication Algorithms
  4959. 15.1.2 Karatsuba Multiplication
  4960. -------------------------------
  4961. The Karatsuba multiplication algorithm is described in Knuth section
  4962. 4.3.3 part A, and various other textbooks. A brief description is given
  4963. here.
  4964. The inputs x and y are treated as each split into two parts of equal
  4965. length (or the most significant part one limb shorter if N is odd).
  4966. high low
  4967. +----------+----------+
  4968. | x1 | x0 |
  4969. +----------+----------+
  4970. +----------+----------+
  4971. | y1 | y0 |
  4972. +----------+----------+
  4973. Let b be the power of 2 where the split occurs, i.e. if x0 is k limbs
  4974. (y0 the same) then b=2^(k*mp_bits_per_limb). With that x=x1*b+x0 and
  4975. y=y1*b+y0, and the following holds,
  4976. x*y = (b^2+b)*x1*y1 - b*(x1-x0)*(y1-y0) + (b+1)*x0*y0
  4977. This formula means doing only three multiplies of (N/2)x(N/2) limbs,
  4978. whereas a basecase multiply of NxN limbs is equivalent to four
  4979. multiplies of (N/2)x(N/2). The factors (b^2+b) etc represent the
  4980. positions where the three products must be added.
  4981. high low
  4982. +--------+--------+ +--------+--------+
  4983. | x1*y1 | | x0*y0 |
  4984. +--------+--------+ +--------+--------+
  4985. +--------+--------+
  4986. add | x1*y1 |
  4987. +--------+--------+
  4988. +--------+--------+
  4989. add | x0*y0 |
  4990. +--------+--------+
  4991. +--------+--------+
  4992. sub | (x1-x0)*(y1-y0) |
  4993. +--------+--------+
  4994. The term (x1-x0)*(y1-y0) is best calculated as an absolute value, and
  4995. the sign used to choose to add or subtract. Notice the sum
  4996. high(x0*y0)+low(x1*y1) occurs twice, so it's possible to do 5*k limb
  4997. additions, rather than 6*k, but in GMP extra function call overheads
  4998. outweigh the saving.
  4999. Squaring is similar to multiplying, but with x=y the formula reduces
  5000. to an equivalent with three squares,
  5001. x^2 = (b^2+b)*x1^2 - b*(x1-x0)^2 + (b+1)*x0^2
  5002. The final result is accumulated from those three squares the same way
  5003. as for the three multiplies above. The middle term (x1-x0)^2 is now
  5004. always positive.
  5005. A similar formula for both multiplying and squaring can be
  5006. constructed with a middle term (x1+x0)*(y1+y0). But those sums can
  5007. exceed k limbs, leading to more carry handling and additions than the
  5008. form above.
  5009. Karatsuba multiplication is asymptotically an O(N^1.585) algorithm,
  5010. the exponent being log(3)/log(2), representing 3 multiplies each 1/2 the
  5011. size of the inputs. This is a big improvement over the basecase
  5012. multiply at O(N^2) and the advantage soon overcomes the extra additions
  5013. Karatsuba performs. 'MUL_TOOM22_THRESHOLD' can be as little as 10
  5014. limbs. The 'SQR' threshold is usually about twice the 'MUL'.
  5015. The basecase algorithm will take a time of the form M(N) = a*N^2 +
  5016. b*N + c and the Karatsuba algorithm K(N) = 3*M(N/2) + d*N + e, which
  5017. expands to K(N) = 3/4*a*N^2 + 3/2*b*N + 3*c + d*N + e. The factor 3/4
  5018. for a means per-crossproduct speedups in the basecase code will increase
  5019. the threshold since they benefit M(N) more than K(N). And conversely the
  5020. 3/2 for b means linear style speedups of b will increase the threshold
  5021. since they benefit K(N) more than M(N). The latter can be seen for
  5022. instance when adding an optimized 'mpn_sqr_diagonal' to
  5023. 'mpn_sqr_basecase'. Of course all speedups reduce total time, and in
  5024. that sense the algorithm thresholds are merely of academic interest.
  5025. 
  5026. File: gmp.info, Node: Toom 3-Way Multiplication, Next: Toom 4-Way Multiplication, Prev: Karatsuba Multiplication, Up: Multiplication Algorithms
  5027. 15.1.3 Toom 3-Way Multiplication
  5028. --------------------------------
  5029. The Karatsuba formula is the simplest case of a general approach to
  5030. splitting inputs that leads to both Toom and FFT algorithms. A
  5031. description of Toom can be found in Knuth section 4.3.3, with an example
  5032. 3-way calculation after Theorem A. The 3-way form used in GMP is
  5033. described here.
  5034. The operands are each considered split into 3 pieces of equal length
  5035. (or the most significant part 1 or 2 limbs shorter than the other two).
  5036. high low
  5037. +----------+----------+----------+
  5038. | x2 | x1 | x0 |
  5039. +----------+----------+----------+
  5040. +----------+----------+----------+
  5041. | y2 | y1 | y0 |
  5042. +----------+----------+----------+
  5043. These parts are treated as the coefficients of two polynomials
  5044. X(t) = x2*t^2 + x1*t + x0
  5045. Y(t) = y2*t^2 + y1*t + y0
  5046. Let b equal the power of 2 which is the size of the x0, x1, y0 and y1
  5047. pieces, i.e. if they're k limbs each then b=2^(k*mp_bits_per_limb).
  5048. With this x=X(b) and y=Y(b).
  5049. Let a polynomial W(t)=X(t)*Y(t) and suppose its coefficients are
  5050. W(t) = w4*t^4 + w3*t^3 + w2*t^2 + w1*t + w0
  5051. The w[i] are going to be determined, and when they are they'll give
  5052. the final result using w=W(b), since x*y=X(b)*Y(b)=W(b). The
  5053. coefficients will be roughly b^2 each, and the final W(b) will be an
  5054. addition like,
  5055. high low
  5056. +-------+-------+
  5057. | w4 |
  5058. +-------+-------+
  5059. +--------+-------+
  5060. | w3 |
  5061. +--------+-------+
  5062. +--------+-------+
  5063. | w2 |
  5064. +--------+-------+
  5065. +--------+-------+
  5066. | w1 |
  5067. +--------+-------+
  5068. +-------+-------+
  5069. | w0 |
  5070. +-------+-------+
  5071. The w[i] coefficients could be formed by a simple set of cross
  5072. products, like w4=x2*y2, w3=x2*y1+x1*y2, w2=x2*y0+x1*y1+x0*y2 etc, but
  5073. this would need all nine x[i]*y[j] for i,j=0,1,2, and would be
  5074. equivalent merely to a basecase multiply. Instead the following
  5075. approach is used.
  5076. X(t) and Y(t) are evaluated and multiplied at 5 points, giving values
  5077. of W(t) at those points. In GMP the following points are used,
  5078. Point Value
  5079. t=0 x0 * y0, which gives w0 immediately
  5080. t=1 (x2+x1+x0) * (y2+y1+y0)
  5081. t=-1 (x2-x1+x0) * (y2-y1+y0)
  5082. t=2 (4*x2+2*x1+x0) * (4*y2+2*y1+y0)
  5083. t=inf x2 * y2, which gives w4 immediately
  5084. At t=-1 the values can be negative and that's handled using the
  5085. absolute values and tracking the sign separately. At t=inf the value is
  5086. actually X(t)*Y(t)/t^4 in the limit as t approaches infinity, but it's
  5087. much easier to think of as simply x2*y2 giving w4 immediately (much like
  5088. x0*y0 at t=0 gives w0 immediately).
  5089. Each of the points substituted into W(t)=w4*t^4+...+w0 gives a linear
  5090. combination of the w[i] coefficients, and the value of those
  5091. combinations has just been calculated.
  5092. W(0) = w0
  5093. W(1) = w4 + w3 + w2 + w1 + w0
  5094. W(-1) = w4 - w3 + w2 - w1 + w0
  5095. W(2) = 16*w4 + 8*w3 + 4*w2 + 2*w1 + w0
  5096. W(inf) = w4
  5097. This is a set of five equations in five unknowns, and some elementary
  5098. linear algebra quickly isolates each w[i]. This involves adding or
  5099. subtracting one W(t) value from another, and a couple of divisions by
  5100. powers of 2 and one division by 3, the latter using the special
  5101. 'mpn_divexact_by3' (*note Exact Division::).
  5102. The conversion of W(t) values to the coefficients is interpolation.
  5103. A polynomial of degree 4 like W(t) is uniquely determined by values
  5104. known at 5 different points. The points are arbitrary and can be chosen
  5105. to make the linear equations come out with a convenient set of steps for
  5106. quickly isolating the w[i].
  5107. Squaring follows the same procedure as multiplication, but there's
  5108. only one X(t) and it's evaluated at the 5 points, and those values
  5109. squared to give values of W(t). The interpolation is then identical,
  5110. and in fact the same 'toom_interpolate_5pts' subroutine is used for both
  5111. squaring and multiplying.
  5112. Toom-3 is asymptotically O(N^1.465), the exponent being
  5113. log(5)/log(3), representing 5 recursive multiplies of 1/3 the original
  5114. size each. This is an improvement over Karatsuba at O(N^1.585), though
  5115. Toom does more work in the evaluation and interpolation and so it only
  5116. realizes its advantage above a certain size.
  5117. Near the crossover between Toom-3 and Karatsuba there's generally a
  5118. range of sizes where the difference between the two is small.
  5119. 'MUL_TOOM33_THRESHOLD' is a somewhat arbitrary point in that range and
  5120. successive runs of the tune program can give different values due to
  5121. small variations in measuring. A graph of time versus size for the two
  5122. shows the effect, see 'tune/README'.
  5123. At the fairly small sizes where the Toom-3 thresholds occur it's
  5124. worth remembering that the asymptotic behaviour for Karatsuba and Toom-3
  5125. can't be expected to make accurate predictions, due of course to the big
  5126. influence of all sorts of overheads, and the fact that only a few
  5127. recursions of each are being performed. Even at large sizes there's a
  5128. good chance machine dependent effects like cache architecture will mean
  5129. actual performance deviates from what might be predicted.
  5130. The formula given for the Karatsuba algorithm (*note Karatsuba
  5131. Multiplication::) has an equivalent for Toom-3 involving only five
  5132. multiplies, but this would be complicated and unenlightening.
  5133. An alternate view of Toom-3 can be found in Zuras (*note
  5134. References::), using a vector to represent the x and y splits and a
  5135. matrix multiplication for the evaluation and interpolation stages. The
  5136. matrix inverses are not meant to be actually used, and they have
  5137. elements with values much greater than in fact arise in the
  5138. interpolation steps. The diagram shown for the 3-way is attractive, but
  5139. again doesn't have to be implemented that way and for example with a bit
  5140. of rearrangement just one division by 6 can be done.
  5141. 
  5142. File: gmp.info, Node: Toom 4-Way Multiplication, Next: Higher degree Toom'n'half, Prev: Toom 3-Way Multiplication, Up: Multiplication Algorithms
  5143. 15.1.4 Toom 4-Way Multiplication
  5144. --------------------------------
  5145. Karatsuba and Toom-3 split the operands into 2 and 3 coefficients,
  5146. respectively. Toom-4 analogously splits the operands into 4
  5147. coefficients. Using the notation from the section on Toom-3
  5148. multiplication, we form two polynomials:
  5149. X(t) = x3*t^3 + x2*t^2 + x1*t + x0
  5150. Y(t) = y3*t^3 + y2*t^2 + y1*t + y0
  5151. X(t) and Y(t) are evaluated and multiplied at 7 points, giving values
  5152. of W(t) at those points. In GMP the following points are used,
  5153. Point Value
  5154. t=0 x0 * y0, which gives w0 immediately
  5155. t=1/2 (x3+2*x2+4*x1+8*x0) * (y3+2*y2+4*y1+8*y0)
  5156. t=-1/2 (-x3+2*x2-4*x1+8*x0) * (-y3+2*y2-4*y1+8*y0)
  5157. t=1 (x3+x2+x1+x0) * (y3+y2+y1+y0)
  5158. t=-1 (-x3+x2-x1+x0) * (-y3+y2-y1+y0)
  5159. t=2 (8*x3+4*x2+2*x1+x0) * (8*y3+4*y2+2*y1+y0)
  5160. t=inf x3 * y3, which gives w6 immediately
  5161. The number of additions and subtractions for Toom-4 is much larger
  5162. than for Toom-3. But several subexpressions occur multiple times, for
  5163. example x2+x0, occurs for both t=1 and t=-1.
  5164. Toom-4 is asymptotically O(N^1.404), the exponent being
  5165. log(7)/log(4), representing 7 recursive multiplies of 1/4 the original
  5166. size each.
  5167. 
  5168. File: gmp.info, Node: Higher degree Toom'n'half, Next: FFT Multiplication, Prev: Toom 4-Way Multiplication, Up: Multiplication Algorithms
  5169. 15.1.5 Higher degree Toom'n'half
  5170. --------------------------------
  5171. The Toom algorithms described above (*note Toom 3-Way Multiplication::,
  5172. *note Toom 4-Way Multiplication::) generalizes to split into an
  5173. arbitrary number of pieces. In general a split of two equally long
  5174. operands into r pieces leads to evaluations and pointwise
  5175. multiplications done at 2*r-1 points. To fully exploit symmetries it
  5176. would be better to have a multiple of 4 points, that's why for higher
  5177. degree Toom'n'half is used.
  5178. Toom'n'half means that the existence of one more piece is considered
  5179. for a single operand. It can be virtual, i.e. zero, or real, when the
  5180. two operand are not exactly balanced. By choosing an even r, Toom-r+1/2
  5181. requires 2r points, a multiple of four.
  5182. The four-plets of points include 0, inf, +1, -1 and +-2^i, +-2^-i .
  5183. Each of them giving shortcuts for the evaluation phase and for some
  5184. steps in the interpolation phase. Further tricks are used to reduce the
  5185. memory footprint of the whole multiplication algorithm to a memory
  5186. buffer equanl in size to the result of the product.
  5187. Current GMP uses both Toom-6'n'half and Toom-8'n'half.
  5188. 
  5189. File: gmp.info, Node: FFT Multiplication, Next: Other Multiplication, Prev: Higher degree Toom'n'half, Up: Multiplication Algorithms
  5190. 15.1.6 FFT Multiplication
  5191. -------------------------
  5192. At large to very large sizes a Fermat style FFT multiplication is used,
  5193. following Schönhage and Strassen (*note References::). Descriptions of
  5194. FFTs in various forms can be found in many textbooks, for instance Knuth
  5195. section 4.3.3 part C or Lipson chapter IX. A brief description of the
  5196. form used in GMP is given here.
  5197. The multiplication done is x*y mod 2^N+1, for a given N. A full
  5198. product x*y is obtained by choosing N>=bits(x)+bits(y) and padding x and
  5199. y with high zero limbs. The modular product is the native form for the
  5200. algorithm, so padding to get a full product is unavoidable.
  5201. The algorithm follows a split, evaluate, pointwise multiply,
  5202. interpolate and combine similar to that described above for Karatsuba
  5203. and Toom-3. A k parameter controls the split, with an FFT-k splitting
  5204. into 2^k pieces of M=N/2^k bits each. N must be a multiple of
  5205. (2^k)*mp_bits_per_limb so the split falls on limb boundaries, avoiding
  5206. bit shifts in the split and combine stages.
  5207. The evaluations, pointwise multiplications, and interpolation, are
  5208. all done modulo 2^N'+1 where N' is 2M+k+3 rounded up to a multiple of
  5209. 2^k and of 'mp_bits_per_limb'. The results of interpolation will be the
  5210. following negacyclic convolution of the input pieces, and the choice of
  5211. N' ensures these sums aren't truncated.
  5212. ---
  5213. \ b
  5214. w[n] = / (-1) * x[i] * y[j]
  5215. ---
  5216. i+j==b*2^k+n
  5217. b=0,1
  5218. The points used for the evaluation are g^i for i=0 to 2^k-1 where
  5219. g=2^(2N'/2^k). g is a 2^k'th root of unity mod 2^N'+1, which produces
  5220. necessary cancellations at the interpolation stage, and it's also a
  5221. power of 2 so the fast Fourier transforms used for the evaluation and
  5222. interpolation do only shifts, adds and negations.
  5223. The pointwise multiplications are done modulo 2^N'+1 and either
  5224. recurse into a further FFT or use a plain multiplication (Toom-3,
  5225. Karatsuba or basecase), whichever is optimal at the size N'. The
  5226. interpolation is an inverse fast Fourier transform. The resulting set
  5227. of sums of x[i]*y[j] are added at appropriate offsets to give the final
  5228. result.
  5229. Squaring is the same, but x is the only input so it's one transform
  5230. at the evaluate stage and the pointwise multiplies are squares. The
  5231. interpolation is the same.
  5232. For a mod 2^N+1 product, an FFT-k is an O(N^(k/(k-1))) algorithm, the
  5233. exponent representing 2^k recursed modular multiplies each 1/2^(k-1) the
  5234. size of the original. Each successive k is an asymptotic improvement,
  5235. but overheads mean each is only faster at bigger and bigger sizes. In
  5236. the code, 'MUL_FFT_TABLE' and 'SQR_FFT_TABLE' are the thresholds where
  5237. each k is used. Each new k effectively swaps some multiplying for some
  5238. shifts, adds and overheads.
  5239. A mod 2^N+1 product can be formed with a normal NxN->2N bit multiply
  5240. plus a subtraction, so an FFT and Toom-3 etc can be compared directly.
  5241. A k=4 FFT at O(N^1.333) can be expected to be the first faster than
  5242. Toom-3 at O(N^1.465). In practice this is what's found, with
  5243. 'MUL_FFT_MODF_THRESHOLD' and 'SQR_FFT_MODF_THRESHOLD' being between 300
  5244. and 1000 limbs, depending on the CPU. So far it's been found that only
  5245. very large FFTs recurse into pointwise multiplies above these sizes.
  5246. When an FFT is to give a full product, the change of N to 2N doesn't
  5247. alter the theoretical complexity for a given k, but for the purposes of
  5248. considering where an FFT might be first used it can be assumed that the
  5249. FFT is recursing into a normal multiply and that on that basis it's
  5250. doing 2^k recursed multiplies each 1/2^(k-2) the size of the inputs,
  5251. making it O(N^(k/(k-2))). This would mean k=7 at O(N^1.4) would be the
  5252. first FFT faster than Toom-3. In practice 'MUL_FFT_THRESHOLD' and
  5253. 'SQR_FFT_THRESHOLD' have been found to be in the k=8 range, somewhere
  5254. between 3000 and 10000 limbs.
  5255. The way N is split into 2^k pieces and then 2M+k+3 is rounded up to a
  5256. multiple of 2^k and 'mp_bits_per_limb' means that when
  5257. 2^k>=mp\_bits\_per\_limb the effective N is a multiple of 2^(2k-1) bits.
  5258. The +k+3 means some values of N just under such a multiple will be
  5259. rounded to the next. The complexity calculations above assume that a
  5260. favourable size is used, meaning one which isn't padded through
  5261. rounding, and it's also assumed that the extra +k+3 bits are negligible
  5262. at typical FFT sizes.
  5263. The practical effect of the 2^(2k-1) constraint is to introduce a
  5264. step-effect into measured speeds. For example k=8 will round N up to a
  5265. multiple of 32768 bits, so for a 32-bit limb there'll be 512 limb groups
  5266. of sizes for which 'mpn_mul_n' runs at the same speed. Or for k=9
  5267. groups of 2048 limbs, k=10 groups of 8192 limbs, etc. In practice it's
  5268. been found each k is used at quite small multiples of its size
  5269. constraint and so the step effect is quite noticeable in a time versus
  5270. size graph.
  5271. The threshold determinations currently measure at the mid-points of
  5272. size steps, but this is sub-optimal since at the start of a new step it
  5273. can happen that it's better to go back to the previous k for a while.
  5274. Something more sophisticated for 'MUL_FFT_TABLE' and 'SQR_FFT_TABLE'
  5275. will be needed.
  5276. 
  5277. File: gmp.info, Node: Other Multiplication, Next: Unbalanced Multiplication, Prev: FFT Multiplication, Up: Multiplication Algorithms
  5278. 15.1.7 Other Multiplication
  5279. ---------------------------
  5280. The Toom algorithms described above (*note Toom 3-Way Multiplication::,
  5281. *note Toom 4-Way Multiplication::) generalizes to split into an
  5282. arbitrary number of pieces, as per Knuth section 4.3.3 algorithm C.
  5283. This is not currently used. The notes here are merely for interest.
  5284. In general a split into r+1 pieces is made, and evaluations and
  5285. pointwise multiplications done at 2*r+1 points. A 4-way split does 7
  5286. pointwise multiplies, 5-way does 9, etc. Asymptotically an (r+1)-way
  5287. algorithm is O(N^(log(2*r+1)/log(r+1))). Only the pointwise
  5288. multiplications count towards big-O complexity, but the time spent in
  5289. the evaluate and interpolate stages grows with r and has a significant
  5290. practical impact, with the asymptotic advantage of each r realized only
  5291. at bigger and bigger sizes. The overheads grow as O(N*r), whereas in an
  5292. r=2^k FFT they grow only as O(N*log(r)).
  5293. Knuth algorithm C evaluates at points 0,1,2,...,2*r, but exercise 4
  5294. uses -r,...,0,...,r and the latter saves some small multiplies in the
  5295. evaluate stage (or rather trades them for additions), and has a further
  5296. saving of nearly half the interpolate steps. The idea is to separate
  5297. odd and even final coefficients and then perform algorithm C steps C7
  5298. and C8 on them separately. The divisors at step C7 become j^2 and the
  5299. multipliers at C8 become 2*t*j-j^2.
  5300. Splitting odd and even parts through positive and negative points can
  5301. be thought of as using -1 as a square root of unity. If a 4th root of
  5302. unity was available then a further split and speedup would be possible,
  5303. but no such root exists for plain integers. Going to complex integers
  5304. with i=sqrt(-1) doesn't help, essentially because in Cartesian form it
  5305. takes three real multiplies to do a complex multiply. The existence of
  5306. 2^k'th roots of unity in a suitable ring or field lets the fast Fourier
  5307. transform keep splitting and get to O(N*log(r)).
  5308. Floating point FFTs use complex numbers approximating Nth roots of
  5309. unity. Some processors have special support for such FFTs. But these
  5310. are not used in GMP since it's very difficult to guarantee an exact
  5311. result (to some number of bits). An occasional difference of 1 in the
  5312. last bit might not matter to a typical signal processing algorithm, but
  5313. is of course of vital importance to GMP.
  5314. 
  5315. File: gmp.info, Node: Unbalanced Multiplication, Prev: Other Multiplication, Up: Multiplication Algorithms
  5316. 15.1.8 Unbalanced Multiplication
  5317. --------------------------------
  5318. Multiplication of operands with different sizes, both below
  5319. 'MUL_TOOM22_THRESHOLD' are done with plain schoolbook multiplication
  5320. (*note Basecase Multiplication::).
  5321. For really large operands, we invoke FFT directly.
  5322. For operands between these sizes, we use Toom inspired algorithms
  5323. suggested by Alberto Zanoni and Marco Bodrato. The idea is to split the
  5324. operands into polynomials of different degree. GMP currently splits the
  5325. smaller operand onto 2 coefficients, i.e., a polynomial of degree 1, but
  5326. the larger operand can be split into 2, 3, or 4 coefficients, i.e., a
  5327. polynomial of degree 1 to 3.
  5328. 
  5329. File: gmp.info, Node: Division Algorithms, Next: Greatest Common Divisor Algorithms, Prev: Multiplication Algorithms, Up: Algorithms
  5330. 15.2 Division Algorithms
  5331. ========================
  5332. * Menu:
  5333. * Single Limb Division::
  5334. * Basecase Division::
  5335. * Divide and Conquer Division::
  5336. * Block-Wise Barrett Division::
  5337. * Exact Division::
  5338. * Exact Remainder::
  5339. * Small Quotient Division::
  5340. 
  5341. File: gmp.info, Node: Single Limb Division, Next: Basecase Division, Prev: Division Algorithms, Up: Division Algorithms
  5342. 15.2.1 Single Limb Division
  5343. ---------------------------
  5344. Nx1 division is implemented using repeated 2x1 divisions from high to
  5345. low, either with a hardware divide instruction or a multiplication by
  5346. inverse, whichever is best on a given CPU.
  5347. The multiply by inverse follows "Improved division by invariant
  5348. integers" by Möller and Granlund (*note References::) and is implemented
  5349. as 'udiv_qrnnd_preinv' in 'gmp-impl.h'. The idea is to have a
  5350. fixed-point approximation to 1/d (see 'invert_limb') and then multiply
  5351. by the high limb (plus one bit) of the dividend to get a quotient q.
  5352. With d normalized (high bit set), q is no more than 1 too small.
  5353. Subtracting q*d from the dividend gives a remainder, and reveals whether
  5354. q or q-1 is correct.
  5355. The result is a division done with two multiplications and four or
  5356. five arithmetic operations. On CPUs with low latency multipliers this
  5357. can be much faster than a hardware divide, though the cost of
  5358. calculating the inverse at the start may mean it's only better on inputs
  5359. bigger than say 4 or 5 limbs.
  5360. When a divisor must be normalized, either for the generic C
  5361. '__udiv_qrnnd_c' or the multiply by inverse, the division performed is
  5362. actually a*2^k by d*2^k where a is the dividend and k is the power
  5363. necessary to have the high bit of d*2^k set. The bit shifts for the
  5364. dividend are usually accomplished "on the fly" meaning by extracting the
  5365. appropriate bits at each step. Done this way the quotient limbs come
  5366. out aligned ready to store. When only the remainder is wanted, an
  5367. alternative is to take the dividend limbs unshifted and calculate r = a
  5368. mod d*2^k followed by an extra final step r*2^k mod d*2^k. This can
  5369. help on CPUs with poor bit shifts or few registers.
  5370. The multiply by inverse can be done two limbs at a time. The
  5371. calculation is basically the same, but the inverse is two limbs and the
  5372. divisor treated as if padded with a low zero limb. This means more
  5373. work, since the inverse will need a 2x2 multiply, but the four 1x1s to
  5374. do that are independent and can therefore be done partly or wholly in
  5375. parallel. Likewise for a 2x1 calculating q*d. The net effect is to
  5376. process two limbs with roughly the same two multiplies worth of latency
  5377. that one limb at a time gives. This extends to 3 or 4 limbs at a time,
  5378. though the extra work to apply the inverse will almost certainly soon
  5379. reach the limits of multiplier throughput.
  5380. A similar approach in reverse can be taken to process just half a
  5381. limb at a time if the divisor is only a half limb. In this case the 1x1
  5382. multiply for the inverse effectively becomes two (1/2)x1 for each limb,
  5383. which can be a saving on CPUs with a fast half limb multiply, or in fact
  5384. if the only multiply is a half limb, and especially if it's not
  5385. pipelined.
  5386. 
  5387. File: gmp.info, Node: Basecase Division, Next: Divide and Conquer Division, Prev: Single Limb Division, Up: Division Algorithms
  5388. 15.2.2 Basecase Division
  5389. ------------------------
  5390. Basecase NxM division is like long division done by hand, but in base
  5391. 2^mp_bits_per_limb. See Knuth section 4.3.1 algorithm D, and
  5392. 'mpn/generic/sb_divrem_mn.c'.
  5393. Briefly stated, while the dividend remains larger than the divisor, a
  5394. high quotient limb is formed and the Nx1 product q*d subtracted at the
  5395. top end of the dividend. With a normalized divisor (most significant
  5396. bit set), each quotient limb can be formed with a 2x1 division and a 1x1
  5397. multiplication plus some subtractions. The 2x1 division is by the high
  5398. limb of the divisor and is done either with a hardware divide or a
  5399. multiply by inverse (the same as in *note Single Limb Division::)
  5400. whichever is faster. Such a quotient is sometimes one too big,
  5401. requiring an addback of the divisor, but that happens rarely.
  5402. With Q=N-M being the number of quotient limbs, this is an O(Q*M)
  5403. algorithm and will run at a speed similar to a basecase QxM
  5404. multiplication, differing in fact only in the extra multiply and divide
  5405. for each of the Q quotient limbs.
  5406. 
  5407. File: gmp.info, Node: Divide and Conquer Division, Next: Block-Wise Barrett Division, Prev: Basecase Division, Up: Division Algorithms
  5408. 15.2.3 Divide and Conquer Division
  5409. ----------------------------------
  5410. For divisors larger than 'DC_DIV_QR_THRESHOLD', division is done by
  5411. dividing. Or to be precise by a recursive divide and conquer algorithm
  5412. based on work by Moenck and Borodin, Jebelean, and Burnikel and Ziegler
  5413. (*note References::).
  5414. The algorithm consists essentially of recognising that a 2NxN
  5415. division can be done with the basecase division algorithm (*note
  5416. Basecase Division::), but using N/2 limbs as a base, not just a single
  5417. limb. This way the multiplications that arise are (N/2)x(N/2) and can
  5418. take advantage of Karatsuba and higher multiplication algorithms (*note
  5419. Multiplication Algorithms::). The two "digits" of the quotient are
  5420. formed by recursive Nx(N/2) divisions.
  5421. If the (N/2)x(N/2) multiplies are done with a basecase multiplication
  5422. then the work is about the same as a basecase division, but with more
  5423. function call overheads and with some subtractions separated from the
  5424. multiplies. These overheads mean that it's only when N/2 is above
  5425. 'MUL_TOOM22_THRESHOLD' that divide and conquer is of use.
  5426. 'DC_DIV_QR_THRESHOLD' is based on the divisor size N, so it will be
  5427. somewhere above twice 'MUL_TOOM22_THRESHOLD', but how much above depends
  5428. on the CPU. An optimized 'mpn_mul_basecase' can lower
  5429. 'DC_DIV_QR_THRESHOLD' a little by offering a ready-made advantage over
  5430. repeated 'mpn_submul_1' calls.
  5431. Divide and conquer is asymptotically O(M(N)*log(N)) where M(N) is the
  5432. time for an NxN multiplication done with FFTs. The actual time is a sum
  5433. over multiplications of the recursed sizes, as can be seen near the end
  5434. of section 2.2 of Burnikel and Ziegler. For example, within the Toom-3
  5435. range, divide and conquer is 2.63*M(N). With higher algorithms the M(N)
  5436. term improves and the multiplier tends to log(N). In practice, at
  5437. moderate to large sizes, a 2NxN division is about 2 to 4 times slower
  5438. than an NxN multiplication.
  5439. 
  5440. File: gmp.info, Node: Block-Wise Barrett Division, Next: Exact Division, Prev: Divide and Conquer Division, Up: Division Algorithms
  5441. 15.2.4 Block-Wise Barrett Division
  5442. ----------------------------------
  5443. For the largest divisions, a block-wise Barrett division algorithm is
  5444. used. Here, the divisor is inverted to a precision determined by the
  5445. relative size of the dividend and divisor. Blocks of quotient limbs are
  5446. then generated by multiplying blocks from the dividend by the inverse.
  5447. Our block-wise algorithm computes a smaller inverse than in the plain
  5448. Barrett algorithm. For a 2n/n division, the inverse will be just
  5449. ceil(n/2) limbs.
  5450. 
  5451. File: gmp.info, Node: Exact Division, Next: Exact Remainder, Prev: Block-Wise Barrett Division, Up: Division Algorithms
  5452. 15.2.5 Exact Division
  5453. ---------------------
  5454. A so-called exact division is when the dividend is known to be an exact
  5455. multiple of the divisor. Jebelean's exact division algorithm uses this
  5456. knowledge to make some significant optimizations (*note References::).
  5457. The idea can be illustrated in decimal for example with 368154
  5458. divided by 543. Because the low digit of the dividend is 4, the low
  5459. digit of the quotient must be 8. This is arrived at from 4*7 mod 10,
  5460. using the fact 7 is the modular inverse of 3 (the low digit of the
  5461. divisor), since 3*7 == 1 mod 10. So 8*543=4344 can be subtracted from
  5462. the dividend leaving 363810. Notice the low digit has become zero.
  5463. The procedure is repeated at the second digit, with the next quotient
  5464. digit 7 (7 == 1*7 mod 10), subtracting 7*543=3801, leaving 325800. And
  5465. finally at the third digit with quotient digit 6 (8*7 mod 10),
  5466. subtracting 6*543=3258 leaving 0. So the quotient is 678.
  5467. Notice however that the multiplies and subtractions don't need to
  5468. extend past the low three digits of the dividend, since that's enough to
  5469. determine the three quotient digits. For the last quotient digit no
  5470. subtraction is needed at all. On a 2NxN division like this one, only
  5471. about half the work of a normal basecase division is necessary.
  5472. For an NxM exact division producing Q=N-M quotient limbs, the saving
  5473. over a normal basecase division is in two parts. Firstly, each of the Q
  5474. quotient limbs needs only one multiply, not a 2x1 divide and multiply.
  5475. Secondly, the crossproducts are reduced when Q>M to Q*M-M*(M+1)/2, or
  5476. when Q<=M to Q*(Q-1)/2. Notice the savings are complementary. If Q is
  5477. big then many divisions are saved, or if Q is small then the
  5478. crossproducts reduce to a small number.
  5479. The modular inverse used is calculated efficiently by 'binvert_limb'
  5480. in 'gmp-impl.h'. This does four multiplies for a 32-bit limb, or six
  5481. for a 64-bit limb. 'tune/modlinv.c' has some alternate implementations
  5482. that might suit processors better at bit twiddling than multiplying.
  5483. The sub-quadratic exact division described by Jebelean in "Exact
  5484. Division with Karatsuba Complexity" is not currently implemented. It
  5485. uses a rearrangement similar to the divide and conquer for normal
  5486. division (*note Divide and Conquer Division::), but operating from low
  5487. to high. A further possibility not currently implemented is
  5488. "Bidirectional Exact Integer Division" by Krandick and Jebelean which
  5489. forms quotient limbs from both the high and low ends of the dividend,
  5490. and can halve once more the number of crossproducts needed in a 2NxN
  5491. division.
  5492. A special case exact division by 3 exists in 'mpn_divexact_by3',
  5493. supporting Toom-3 multiplication and 'mpq' canonicalizations. It forms
  5494. quotient digits with a multiply by the modular inverse of 3 (which is
  5495. '0xAA..AAB') and uses two comparisons to determine a borrow for the next
  5496. limb. The multiplications don't need to be on the dependent chain, as
  5497. long as the effect of the borrows is applied, which can help chips with
  5498. pipelined multipliers.