diophantine.py 120 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980
  1. from __future__ import annotations
  2. from sympy.core.add import Add
  3. from sympy.core.assumptions import check_assumptions
  4. from sympy.core.containers import Tuple
  5. from sympy.core.exprtools import factor_terms
  6. from sympy.core.function import _mexpand
  7. from sympy.core.mul import Mul
  8. from sympy.core.numbers import Rational, int_valued
  9. from sympy.core.intfunc import igcdex, ilcm, igcd, integer_nthroot, isqrt
  10. from sympy.core.relational import Eq
  11. from sympy.core.singleton import S
  12. from sympy.core.sorting import default_sort_key, ordered
  13. from sympy.core.symbol import Symbol, symbols
  14. from sympy.core.sympify import _sympify
  15. from sympy.external.gmpy import jacobi, remove, invert, iroot
  16. from sympy.functions.elementary.complexes import sign
  17. from sympy.functions.elementary.integers import floor
  18. from sympy.functions.elementary.miscellaneous import sqrt
  19. from sympy.matrices.dense import MutableDenseMatrix as Matrix
  20. from sympy.ntheory.factor_ import divisors, factorint, perfect_power
  21. from sympy.ntheory.generate import nextprime
  22. from sympy.ntheory.primetest import is_square, isprime
  23. from sympy.ntheory.modular import symmetric_residue
  24. from sympy.ntheory.residue_ntheory import sqrt_mod, sqrt_mod_iter
  25. from sympy.polys.polyerrors import GeneratorsNeeded
  26. from sympy.polys.polytools import Poly, factor_list
  27. from sympy.simplify.simplify import signsimp
  28. from sympy.solvers.solveset import solveset_real
  29. from sympy.utilities import numbered_symbols
  30. from sympy.utilities.misc import as_int, filldedent
  31. from sympy.utilities.iterables import (is_sequence, subsets, permute_signs,
  32. signed_permutations, ordered_partitions)
  33. # these are imported with 'from sympy.solvers.diophantine import *
  34. __all__ = ['diophantine', 'classify_diop']
  35. class DiophantineSolutionSet(set):
  36. """
  37. Container for a set of solutions to a particular diophantine equation.
  38. The base representation is a set of tuples representing each of the solutions.
  39. Parameters
  40. ==========
  41. symbols : list
  42. List of free symbols in the original equation.
  43. parameters: list
  44. List of parameters to be used in the solution.
  45. Examples
  46. ========
  47. Adding solutions:
  48. >>> from sympy.solvers.diophantine.diophantine import DiophantineSolutionSet
  49. >>> from sympy.abc import x, y, t, u
  50. >>> s1 = DiophantineSolutionSet([x, y], [t, u])
  51. >>> s1
  52. set()
  53. >>> s1.add((2, 3))
  54. >>> s1.add((-1, u))
  55. >>> s1
  56. {(-1, u), (2, 3)}
  57. >>> s2 = DiophantineSolutionSet([x, y], [t, u])
  58. >>> s2.add((3, 4))
  59. >>> s1.update(*s2)
  60. >>> s1
  61. {(-1, u), (2, 3), (3, 4)}
  62. Conversion of solutions into dicts:
  63. >>> list(s1.dict_iterator())
  64. [{x: -1, y: u}, {x: 2, y: 3}, {x: 3, y: 4}]
  65. Substituting values:
  66. >>> s3 = DiophantineSolutionSet([x, y], [t, u])
  67. >>> s3.add((t**2, t + u))
  68. >>> s3
  69. {(t**2, t + u)}
  70. >>> s3.subs({t: 2, u: 3})
  71. {(4, 5)}
  72. >>> s3.subs(t, -1)
  73. {(1, u - 1)}
  74. >>> s3.subs(t, 3)
  75. {(9, u + 3)}
  76. Evaluation at specific values. Positional arguments are given in the same order as the parameters:
  77. >>> s3(-2, 3)
  78. {(4, 1)}
  79. >>> s3(5)
  80. {(25, u + 5)}
  81. >>> s3(None, 2)
  82. {(t**2, t + 2)}
  83. """
  84. def __init__(self, symbols_seq, parameters):
  85. super().__init__()
  86. if not is_sequence(symbols_seq):
  87. raise ValueError("Symbols must be given as a sequence.")
  88. if not is_sequence(parameters):
  89. raise ValueError("Parameters must be given as a sequence.")
  90. self.symbols = tuple(symbols_seq)
  91. self.parameters = tuple(parameters)
  92. def add(self, solution):
  93. if len(solution) != len(self.symbols):
  94. raise ValueError("Solution should have a length of %s, not %s" % (len(self.symbols), len(solution)))
  95. # make solution canonical wrt sign (i.e. no -x unless x is also present as an arg)
  96. args = set(solution)
  97. for i in range(len(solution)):
  98. x = solution[i]
  99. if not type(x) is int and (-x).is_Symbol and -x not in args:
  100. solution = [_.subs(-x, x) for _ in solution]
  101. super().add(Tuple(*solution))
  102. def update(self, *solutions):
  103. for solution in solutions:
  104. self.add(solution)
  105. def dict_iterator(self):
  106. for solution in ordered(self):
  107. yield dict(zip(self.symbols, solution))
  108. def subs(self, *args, **kwargs):
  109. result = DiophantineSolutionSet(self.symbols, self.parameters)
  110. for solution in self:
  111. result.add(solution.subs(*args, **kwargs))
  112. return result
  113. def __call__(self, *args):
  114. if len(args) > len(self.parameters):
  115. raise ValueError("Evaluation should have at most %s values, not %s" % (len(self.parameters), len(args)))
  116. rep = {p: v for p, v in zip(self.parameters, args) if v is not None}
  117. return self.subs(rep)
  118. class DiophantineEquationType:
  119. """
  120. Internal representation of a particular diophantine equation type.
  121. Parameters
  122. ==========
  123. equation :
  124. The diophantine equation that is being solved.
  125. free_symbols : list (optional)
  126. The symbols being solved for.
  127. Attributes
  128. ==========
  129. total_degree :
  130. The maximum of the degrees of all terms in the equation
  131. homogeneous :
  132. Does the equation contain a term of degree 0
  133. homogeneous_order :
  134. Does the equation contain any coefficient that is in the symbols being solved for
  135. dimension :
  136. The number of symbols being solved for
  137. """
  138. name: str
  139. def __init__(self, equation, free_symbols=None):
  140. self.equation = _sympify(equation).expand(force=True)
  141. if free_symbols is not None:
  142. self.free_symbols = free_symbols
  143. else:
  144. self.free_symbols = list(self.equation.free_symbols)
  145. self.free_symbols.sort(key=default_sort_key)
  146. if not self.free_symbols:
  147. raise ValueError('equation should have 1 or more free symbols')
  148. self.coeff = self.equation.as_coefficients_dict()
  149. if not all(int_valued(c) for c in self.coeff.values()):
  150. raise TypeError("Coefficients should be Integers")
  151. self.total_degree = Poly(self.equation).total_degree()
  152. self.homogeneous = 1 not in self.coeff
  153. self.homogeneous_order = not (set(self.coeff) & set(self.free_symbols))
  154. self.dimension = len(self.free_symbols)
  155. self._parameters = None
  156. def matches(self):
  157. """
  158. Determine whether the given equation can be matched to the particular equation type.
  159. """
  160. return False
  161. @property
  162. def n_parameters(self):
  163. return self.dimension
  164. @property
  165. def parameters(self):
  166. if self._parameters is None:
  167. self._parameters = symbols('t_:%i' % (self.n_parameters,), integer=True)
  168. return self._parameters
  169. def solve(self, parameters=None, limit=None) -> DiophantineSolutionSet:
  170. raise NotImplementedError('No solver has been written for %s.' % self.name)
  171. def pre_solve(self, parameters=None):
  172. if not self.matches():
  173. raise ValueError("This equation does not match the %s equation type." % self.name)
  174. if parameters is not None:
  175. if len(parameters) != self.n_parameters:
  176. raise ValueError("Expected %s parameter(s) but got %s" % (self.n_parameters, len(parameters)))
  177. self._parameters = parameters
  178. class Univariate(DiophantineEquationType):
  179. """
  180. Representation of a univariate diophantine equation.
  181. A univariate diophantine equation is an equation of the form
  182. `a_{0} + a_{1}x + a_{2}x^2 + .. + a_{n}x^n = 0` where `a_{1}, a_{2}, ..a_{n}` are
  183. integer constants and `x` is an integer variable.
  184. Examples
  185. ========
  186. >>> from sympy.solvers.diophantine.diophantine import Univariate
  187. >>> from sympy.abc import x
  188. >>> Univariate((x - 2)*(x - 3)**2).solve() # solves equation (x - 2)*(x - 3)**2 == 0
  189. {(2,), (3,)}
  190. """
  191. name = 'univariate'
  192. def matches(self):
  193. return self.dimension == 1
  194. def solve(self, parameters=None, limit=None):
  195. self.pre_solve(parameters)
  196. result = DiophantineSolutionSet(self.free_symbols, parameters=self.parameters)
  197. for i in solveset_real(self.equation, self.free_symbols[0]).intersect(S.Integers):
  198. result.add((i,))
  199. return result
  200. class Linear(DiophantineEquationType):
  201. """
  202. Representation of a linear diophantine equation.
  203. A linear diophantine equation is an equation of the form `a_{1}x_{1} +
  204. a_{2}x_{2} + .. + a_{n}x_{n} = 0` where `a_{1}, a_{2}, ..a_{n}` are
  205. integer constants and `x_{1}, x_{2}, ..x_{n}` are integer variables.
  206. Examples
  207. ========
  208. >>> from sympy.solvers.diophantine.diophantine import Linear
  209. >>> from sympy.abc import x, y, z
  210. >>> l1 = Linear(2*x - 3*y - 5)
  211. >>> l1.matches() # is this equation linear
  212. True
  213. >>> l1.solve() # solves equation 2*x - 3*y - 5 == 0
  214. {(3*t_0 - 5, 2*t_0 - 5)}
  215. Here x = -3*t_0 - 5 and y = -2*t_0 - 5
  216. >>> Linear(2*x - 3*y - 4*z -3).solve()
  217. {(t_0, 2*t_0 + 4*t_1 + 3, -t_0 - 3*t_1 - 3)}
  218. """
  219. name = 'linear'
  220. def matches(self):
  221. return self.total_degree == 1
  222. def solve(self, parameters=None, limit=None):
  223. self.pre_solve(parameters)
  224. coeff = self.coeff
  225. var = self.free_symbols
  226. if 1 in coeff:
  227. # negate coeff[] because input is of the form: ax + by + c == 0
  228. # but is used as: ax + by == -c
  229. c = -coeff[1]
  230. else:
  231. c = 0
  232. result = DiophantineSolutionSet(var, parameters=self.parameters)
  233. params = result.parameters
  234. if len(var) == 1:
  235. q, r = divmod(c, coeff[var[0]])
  236. if not r:
  237. result.add((q,))
  238. return result
  239. '''
  240. base_solution_linear() can solve diophantine equations of the form:
  241. a*x + b*y == c
  242. We break down multivariate linear diophantine equations into a
  243. series of bivariate linear diophantine equations which can then
  244. be solved individually by base_solution_linear().
  245. Consider the following:
  246. a_0*x_0 + a_1*x_1 + a_2*x_2 == c
  247. which can be re-written as:
  248. a_0*x_0 + g_0*y_0 == c
  249. where
  250. g_0 == gcd(a_1, a_2)
  251. and
  252. y == (a_1*x_1)/g_0 + (a_2*x_2)/g_0
  253. This leaves us with two binary linear diophantine equations.
  254. For the first equation:
  255. a == a_0
  256. b == g_0
  257. c == c
  258. For the second:
  259. a == a_1/g_0
  260. b == a_2/g_0
  261. c == the solution we find for y_0 in the first equation.
  262. The arrays A and B are the arrays of integers used for
  263. 'a' and 'b' in each of the n-1 bivariate equations we solve.
  264. '''
  265. A = [coeff[v] for v in var]
  266. B = []
  267. if len(var) > 2:
  268. B.append(igcd(A[-2], A[-1]))
  269. A[-2] = A[-2] // B[0]
  270. A[-1] = A[-1] // B[0]
  271. for i in range(len(A) - 3, 0, -1):
  272. gcd = igcd(B[0], A[i])
  273. B[0] = B[0] // gcd
  274. A[i] = A[i] // gcd
  275. B.insert(0, gcd)
  276. B.append(A[-1])
  277. '''
  278. Consider the trivariate linear equation:
  279. 4*x_0 + 6*x_1 + 3*x_2 == 2
  280. This can be re-written as:
  281. 4*x_0 + 3*y_0 == 2
  282. where
  283. y_0 == 2*x_1 + x_2
  284. (Note that gcd(3, 6) == 3)
  285. The complete integral solution to this equation is:
  286. x_0 == 2 + 3*t_0
  287. y_0 == -2 - 4*t_0
  288. where 't_0' is any integer.
  289. Now that we have a solution for 'x_0', find 'x_1' and 'x_2':
  290. 2*x_1 + x_2 == -2 - 4*t_0
  291. We can then solve for '-2' and '-4' independently,
  292. and combine the results:
  293. 2*x_1a + x_2a == -2
  294. x_1a == 0 + t_0
  295. x_2a == -2 - 2*t_0
  296. 2*x_1b + x_2b == -4*t_0
  297. x_1b == 0*t_0 + t_1
  298. x_2b == -4*t_0 - 2*t_1
  299. ==>
  300. x_1 == t_0 + t_1
  301. x_2 == -2 - 6*t_0 - 2*t_1
  302. where 't_0' and 't_1' are any integers.
  303. Note that:
  304. 4*(2 + 3*t_0) + 6*(t_0 + t_1) + 3*(-2 - 6*t_0 - 2*t_1) == 2
  305. for any integral values of 't_0', 't_1'; as required.
  306. This method is generalised for many variables, below.
  307. '''
  308. solutions = []
  309. for Ai, Bi in zip(A, B):
  310. tot_x, tot_y = [], []
  311. for arg in Add.make_args(c):
  312. if arg.is_Integer:
  313. # example: 5 -> k = 5
  314. k, p = arg, S.One
  315. pnew = params[0]
  316. else: # arg is a Mul or Symbol
  317. # example: 3*t_1 -> k = 3
  318. # example: t_0 -> k = 1
  319. k, p = arg.as_coeff_Mul()
  320. pnew = params[params.index(p) + 1]
  321. sol = sol_x, sol_y = base_solution_linear(k, Ai, Bi, pnew)
  322. if p is S.One:
  323. if None in sol:
  324. return result
  325. else:
  326. # convert a + b*pnew -> a*p + b*pnew
  327. if isinstance(sol_x, Add):
  328. sol_x = sol_x.args[0]*p + sol_x.args[1]
  329. if isinstance(sol_y, Add):
  330. sol_y = sol_y.args[0]*p + sol_y.args[1]
  331. tot_x.append(sol_x)
  332. tot_y.append(sol_y)
  333. solutions.append(Add(*tot_x))
  334. c = Add(*tot_y)
  335. solutions.append(c)
  336. result.add(solutions)
  337. return result
  338. class BinaryQuadratic(DiophantineEquationType):
  339. """
  340. Representation of a binary quadratic diophantine equation.
  341. A binary quadratic diophantine equation is an equation of the
  342. form `Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0`, where `A, B, C, D, E,
  343. F` are integer constants and `x` and `y` are integer variables.
  344. Examples
  345. ========
  346. >>> from sympy.abc import x, y
  347. >>> from sympy.solvers.diophantine.diophantine import BinaryQuadratic
  348. >>> b1 = BinaryQuadratic(x**3 + y**2 + 1)
  349. >>> b1.matches()
  350. False
  351. >>> b2 = BinaryQuadratic(x**2 + y**2 + 2*x + 2*y + 2)
  352. >>> b2.matches()
  353. True
  354. >>> b2.solve()
  355. {(-1, -1)}
  356. References
  357. ==========
  358. .. [1] Methods to solve Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0, [online],
  359. Available: https://www.alpertron.com.ar/METHODS.HTM
  360. .. [2] Solving the equation ax^2+ bxy + cy^2 + dx + ey + f= 0, [online],
  361. Available: https://web.archive.org/web/20160323033111/http://www.jpr2718.org/ax2p.pdf
  362. """
  363. name = 'binary_quadratic'
  364. def matches(self):
  365. return self.total_degree == 2 and self.dimension == 2
  366. def solve(self, parameters=None, limit=None) -> DiophantineSolutionSet:
  367. self.pre_solve(parameters)
  368. var = self.free_symbols
  369. coeff = self.coeff
  370. x, y = var
  371. A = coeff[x**2]
  372. B = coeff[x*y]
  373. C = coeff[y**2]
  374. D = coeff[x]
  375. E = coeff[y]
  376. F = coeff[S.One]
  377. A, B, C, D, E, F = [as_int(i) for i in _remove_gcd(A, B, C, D, E, F)]
  378. # (1) Simple-Hyperbolic case: A = C = 0, B != 0
  379. # In this case equation can be converted to (Bx + E)(By + D) = DE - BF
  380. # We consider two cases; DE - BF = 0 and DE - BF != 0
  381. # More details, https://www.alpertron.com.ar/METHODS.HTM#SHyperb
  382. result = DiophantineSolutionSet(var, self.parameters)
  383. t, u = result.parameters
  384. discr = B**2 - 4*A*C
  385. if A == 0 and C == 0 and B != 0:
  386. if D*E - B*F == 0:
  387. q, r = divmod(E, B)
  388. if not r:
  389. result.add((-q, t))
  390. q, r = divmod(D, B)
  391. if not r:
  392. result.add((t, -q))
  393. else:
  394. div = divisors(D*E - B*F)
  395. div = div + [-term for term in div]
  396. for d in div:
  397. x0, r = divmod(d - E, B)
  398. if not r:
  399. q, r = divmod(D*E - B*F, d)
  400. if not r:
  401. y0, r = divmod(q - D, B)
  402. if not r:
  403. result.add((x0, y0))
  404. # (2) Parabolic case: B**2 - 4*A*C = 0
  405. # There are two subcases to be considered in this case.
  406. # sqrt(c)D - sqrt(a)E = 0 and sqrt(c)D - sqrt(a)E != 0
  407. # More Details, https://www.alpertron.com.ar/METHODS.HTM#Parabol
  408. elif discr == 0:
  409. if A == 0:
  410. s = BinaryQuadratic(self.equation, free_symbols=[y, x]).solve(parameters=[t, u])
  411. for soln in s:
  412. result.add((soln[1], soln[0]))
  413. else:
  414. g = sign(A)*igcd(A, C)
  415. a = A // g
  416. c = C // g
  417. e = sign(B / A)
  418. sqa = isqrt(a)
  419. sqc = isqrt(c)
  420. _c = e*sqc*D - sqa*E
  421. if not _c:
  422. z = Symbol("z", real=True)
  423. eq = sqa*g*z**2 + D*z + sqa*F
  424. roots = solveset_real(eq, z).intersect(S.Integers)
  425. for root in roots:
  426. ans = diop_solve(sqa*x + e*sqc*y - root)
  427. result.add((ans[0], ans[1]))
  428. elif int_valued(c):
  429. solve_x = lambda u: -e*sqc*g*_c*t**2 - (E + 2*e*sqc*g*u)*t \
  430. - (e*sqc*g*u**2 + E*u + e*sqc*F) // _c
  431. solve_y = lambda u: sqa*g*_c*t**2 + (D + 2*sqa*g*u)*t \
  432. + (sqa*g*u**2 + D*u + sqa*F) // _c
  433. for z0 in range(0, abs(_c)):
  434. # Check if the coefficients of y and x obtained are integers or not
  435. if (divisible(sqa*g*z0**2 + D*z0 + sqa*F, _c) and
  436. divisible(e*sqc*g*z0**2 + E*z0 + e*sqc*F, _c)):
  437. result.add((solve_x(z0), solve_y(z0)))
  438. # (3) Method used when B**2 - 4*A*C is a square, is described in p. 6 of the below paper
  439. # by John P. Robertson.
  440. # https://web.archive.org/web/20160323033111/http://www.jpr2718.org/ax2p.pdf
  441. elif is_square(discr):
  442. if A != 0:
  443. r = sqrt(discr)
  444. u, v = symbols("u, v", integer=True)
  445. eq = _mexpand(
  446. 4*A*r*u*v + 4*A*D*(B*v + r*u + r*v - B*u) +
  447. 2*A*4*A*E*(u - v) + 4*A*r*4*A*F)
  448. solution = diop_solve(eq, t)
  449. for s0, t0 in solution:
  450. num = B*t0 + r*s0 + r*t0 - B*s0
  451. x_0 = S(num) / (4*A*r)
  452. y_0 = S(s0 - t0) / (2*r)
  453. if isinstance(s0, Symbol) or isinstance(t0, Symbol):
  454. if len(check_param(x_0, y_0, 4*A*r, parameters)) > 0:
  455. ans = check_param(x_0, y_0, 4*A*r, parameters)
  456. result.update(*ans)
  457. elif x_0.is_Integer and y_0.is_Integer:
  458. if is_solution_quad(var, coeff, x_0, y_0):
  459. result.add((x_0, y_0))
  460. else:
  461. s = BinaryQuadratic(self.equation, free_symbols=var[::-1]).solve(parameters=[t, u]) # Interchange x and y
  462. while s:
  463. result.add(s.pop()[::-1]) # and solution <--------+
  464. # (4) B**2 - 4*A*C > 0 and B**2 - 4*A*C not a square or B**2 - 4*A*C < 0
  465. else:
  466. P, Q = _transformation_to_DN(var, coeff)
  467. D, N = _find_DN(var, coeff)
  468. solns_pell = diop_DN(D, N)
  469. if D < 0:
  470. for x0, y0 in solns_pell:
  471. for x in [-x0, x0]:
  472. for y in [-y0, y0]:
  473. s = P*Matrix([x, y]) + Q
  474. try:
  475. result.add([as_int(_) for _ in s])
  476. except ValueError:
  477. pass
  478. else:
  479. # In this case equation can be transformed into a Pell equation
  480. solns_pell = set(solns_pell)
  481. solns_pell.update((-X, -Y) for X, Y in list(solns_pell))
  482. a = diop_DN(D, 1)
  483. T = a[0][0]
  484. U = a[0][1]
  485. if all(int_valued(_) for _ in P[:4] + Q[:2]):
  486. for r, s in solns_pell:
  487. _a = (r + s*sqrt(D))*(T + U*sqrt(D))**t
  488. _b = (r - s*sqrt(D))*(T - U*sqrt(D))**t
  489. x_n = _mexpand(S(_a + _b) / 2)
  490. y_n = _mexpand(S(_a - _b) / (2*sqrt(D)))
  491. s = P*Matrix([x_n, y_n]) + Q
  492. result.add(s)
  493. else:
  494. L = ilcm(*[_.q for _ in P[:4] + Q[:2]])
  495. k = 1
  496. T_k = T
  497. U_k = U
  498. while (T_k - 1) % L != 0 or U_k % L != 0:
  499. T_k, U_k = T_k*T + D*U_k*U, T_k*U + U_k*T
  500. k += 1
  501. for X, Y in solns_pell:
  502. for i in range(k):
  503. if all(int_valued(_) for _ in P*Matrix([X, Y]) + Q):
  504. _a = (X + sqrt(D)*Y)*(T_k + sqrt(D)*U_k)**t
  505. _b = (X - sqrt(D)*Y)*(T_k - sqrt(D)*U_k)**t
  506. Xt = S(_a + _b) / 2
  507. Yt = S(_a - _b) / (2*sqrt(D))
  508. s = P*Matrix([Xt, Yt]) + Q
  509. result.add(s)
  510. X, Y = X*T + D*U*Y, X*U + Y*T
  511. return result
  512. class InhomogeneousTernaryQuadratic(DiophantineEquationType):
  513. """
  514. Representation of an inhomogeneous ternary quadratic.
  515. No solver is currently implemented for this equation type.
  516. """
  517. name = 'inhomogeneous_ternary_quadratic'
  518. def matches(self):
  519. if not (self.total_degree == 2 and self.dimension == 3):
  520. return False
  521. if not self.homogeneous:
  522. return False
  523. return not self.homogeneous_order
  524. class HomogeneousTernaryQuadraticNormal(DiophantineEquationType):
  525. """
  526. Representation of a homogeneous ternary quadratic normal diophantine equation.
  527. Examples
  528. ========
  529. >>> from sympy.abc import x, y, z
  530. >>> from sympy.solvers.diophantine.diophantine import HomogeneousTernaryQuadraticNormal
  531. >>> HomogeneousTernaryQuadraticNormal(4*x**2 - 5*y**2 + z**2).solve()
  532. {(1, 2, 4)}
  533. """
  534. name = 'homogeneous_ternary_quadratic_normal'
  535. def matches(self):
  536. if not (self.total_degree == 2 and self.dimension == 3):
  537. return False
  538. if not self.homogeneous:
  539. return False
  540. if not self.homogeneous_order:
  541. return False
  542. nonzero = [k for k in self.coeff if self.coeff[k]]
  543. return len(nonzero) == 3 and all(i**2 in nonzero for i in self.free_symbols)
  544. def solve(self, parameters=None, limit=None) -> DiophantineSolutionSet:
  545. self.pre_solve(parameters)
  546. var = self.free_symbols
  547. coeff = self.coeff
  548. x, y, z = var
  549. a = coeff[x**2]
  550. b = coeff[y**2]
  551. c = coeff[z**2]
  552. (sqf_of_a, sqf_of_b, sqf_of_c), (a_1, b_1, c_1), (a_2, b_2, c_2) = \
  553. sqf_normal(a, b, c, steps=True)
  554. A = -a_2*c_2
  555. B = -b_2*c_2
  556. result = DiophantineSolutionSet(var, parameters=self.parameters)
  557. # If following two conditions are satisfied then there are no solutions
  558. if A < 0 and B < 0:
  559. return result
  560. if (
  561. sqrt_mod(-b_2*c_2, a_2) is None or
  562. sqrt_mod(-c_2*a_2, b_2) is None or
  563. sqrt_mod(-a_2*b_2, c_2) is None):
  564. return result
  565. z_0, x_0, y_0 = descent(A, B)
  566. z_0, q = _rational_pq(z_0, abs(c_2))
  567. x_0 *= q
  568. y_0 *= q
  569. x_0, y_0, z_0 = _remove_gcd(x_0, y_0, z_0)
  570. # Holzer reduction
  571. if sign(a) == sign(b):
  572. x_0, y_0, z_0 = holzer(x_0, y_0, z_0, abs(a_2), abs(b_2), abs(c_2))
  573. elif sign(a) == sign(c):
  574. x_0, z_0, y_0 = holzer(x_0, z_0, y_0, abs(a_2), abs(c_2), abs(b_2))
  575. else:
  576. y_0, z_0, x_0 = holzer(y_0, z_0, x_0, abs(b_2), abs(c_2), abs(a_2))
  577. x_0 = reconstruct(b_1, c_1, x_0)
  578. y_0 = reconstruct(a_1, c_1, y_0)
  579. z_0 = reconstruct(a_1, b_1, z_0)
  580. sq_lcm = ilcm(sqf_of_a, sqf_of_b, sqf_of_c)
  581. x_0 = abs(x_0*sq_lcm // sqf_of_a)
  582. y_0 = abs(y_0*sq_lcm // sqf_of_b)
  583. z_0 = abs(z_0*sq_lcm // sqf_of_c)
  584. result.add(_remove_gcd(x_0, y_0, z_0))
  585. return result
  586. class HomogeneousTernaryQuadratic(DiophantineEquationType):
  587. """
  588. Representation of a homogeneous ternary quadratic diophantine equation.
  589. Examples
  590. ========
  591. >>> from sympy.abc import x, y, z
  592. >>> from sympy.solvers.diophantine.diophantine import HomogeneousTernaryQuadratic
  593. >>> HomogeneousTernaryQuadratic(x**2 + y**2 - 3*z**2 + x*y).solve()
  594. {(-1, 2, 1)}
  595. >>> HomogeneousTernaryQuadratic(3*x**2 + y**2 - 3*z**2 + 5*x*y + y*z).solve()
  596. {(3, 12, 13)}
  597. """
  598. name = 'homogeneous_ternary_quadratic'
  599. def matches(self):
  600. if not (self.total_degree == 2 and self.dimension == 3):
  601. return False
  602. if not self.homogeneous:
  603. return False
  604. if not self.homogeneous_order:
  605. return False
  606. nonzero = [k for k in self.coeff if self.coeff[k]]
  607. return not (len(nonzero) == 3 and all(i**2 in nonzero for i in self.free_symbols))
  608. def solve(self, parameters=None, limit=None):
  609. self.pre_solve(parameters)
  610. _var = self.free_symbols
  611. coeff = self.coeff
  612. x, y, z = _var
  613. var = [x, y, z]
  614. # Equations of the form B*x*y + C*z*x + E*y*z = 0 and At least two of the
  615. # coefficients A, B, C are non-zero.
  616. # There are infinitely many solutions for the equation.
  617. # Ex: (0, 0, t), (0, t, 0), (t, 0, 0)
  618. # Equation can be re-written as y*(B*x + E*z) = -C*x*z and we can find rather
  619. # unobvious solutions. Set y = -C and B*x + E*z = x*z. The latter can be solved by
  620. # using methods for binary quadratic diophantine equations. Let's select the
  621. # solution which minimizes |x| + |z|
  622. result = DiophantineSolutionSet(var, parameters=self.parameters)
  623. def unpack_sol(sol):
  624. if len(sol) > 0:
  625. return list(sol)[0]
  626. return None, None, None
  627. if not any(coeff[i**2] for i in var):
  628. if coeff[x*z]:
  629. sols = diophantine(coeff[x*y]*x + coeff[y*z]*z - x*z)
  630. s = min(sols, key=lambda r: abs(r[0]) + abs(r[1]))
  631. result.add(_remove_gcd(s[0], -coeff[x*z], s[1]))
  632. return result
  633. var[0], var[1] = _var[1], _var[0]
  634. y_0, x_0, z_0 = unpack_sol(_diop_ternary_quadratic(var, coeff))
  635. if x_0 is not None:
  636. result.add((x_0, y_0, z_0))
  637. return result
  638. if coeff[x**2] == 0:
  639. # If the coefficient of x is zero change the variables
  640. if coeff[y**2] == 0:
  641. var[0], var[2] = _var[2], _var[0]
  642. z_0, y_0, x_0 = unpack_sol(_diop_ternary_quadratic(var, coeff))
  643. else:
  644. var[0], var[1] = _var[1], _var[0]
  645. y_0, x_0, z_0 = unpack_sol(_diop_ternary_quadratic(var, coeff))
  646. else:
  647. if coeff[x*y] or coeff[x*z]:
  648. # Apply the transformation x --> X - (B*y + C*z)/(2*A)
  649. A = coeff[x**2]
  650. B = coeff[x*y]
  651. C = coeff[x*z]
  652. D = coeff[y**2]
  653. E = coeff[y*z]
  654. F = coeff[z**2]
  655. _coeff = {}
  656. _coeff[x**2] = 4*A**2
  657. _coeff[y**2] = 4*A*D - B**2
  658. _coeff[z**2] = 4*A*F - C**2
  659. _coeff[y*z] = 4*A*E - 2*B*C
  660. _coeff[x*y] = 0
  661. _coeff[x*z] = 0
  662. x_0, y_0, z_0 = unpack_sol(_diop_ternary_quadratic(var, _coeff))
  663. if x_0 is None:
  664. return result
  665. p, q = _rational_pq(B*y_0 + C*z_0, 2*A)
  666. x_0, y_0, z_0 = x_0*q - p, y_0*q, z_0*q
  667. elif coeff[z*y] != 0:
  668. if coeff[y**2] == 0:
  669. if coeff[z**2] == 0:
  670. # Equations of the form A*x**2 + E*yz = 0.
  671. A = coeff[x**2]
  672. E = coeff[y*z]
  673. b, a = _rational_pq(-E, A)
  674. x_0, y_0, z_0 = b, a, b
  675. else:
  676. # Ax**2 + E*y*z + F*z**2 = 0
  677. var[0], var[2] = _var[2], _var[0]
  678. z_0, y_0, x_0 = unpack_sol(_diop_ternary_quadratic(var, coeff))
  679. else:
  680. # A*x**2 + D*y**2 + E*y*z + F*z**2 = 0, C may be zero
  681. var[0], var[1] = _var[1], _var[0]
  682. y_0, x_0, z_0 = unpack_sol(_diop_ternary_quadratic(var, coeff))
  683. else:
  684. # Ax**2 + D*y**2 + F*z**2 = 0, C may be zero
  685. x_0, y_0, z_0 = unpack_sol(_diop_ternary_quadratic_normal(var, coeff))
  686. if x_0 is None:
  687. return result
  688. result.add(_remove_gcd(x_0, y_0, z_0))
  689. return result
  690. class InhomogeneousGeneralQuadratic(DiophantineEquationType):
  691. """
  692. Representation of an inhomogeneous general quadratic.
  693. No solver is currently implemented for this equation type.
  694. """
  695. name = 'inhomogeneous_general_quadratic'
  696. def matches(self):
  697. if not (self.total_degree == 2 and self.dimension >= 3):
  698. return False
  699. if not self.homogeneous_order:
  700. return True
  701. # there may be Pow keys like x**2 or Mul keys like x*y
  702. return any(k.is_Mul for k in self.coeff) and not self.homogeneous
  703. class HomogeneousGeneralQuadratic(DiophantineEquationType):
  704. """
  705. Representation of a homogeneous general quadratic.
  706. No solver is currently implemented for this equation type.
  707. """
  708. name = 'homogeneous_general_quadratic'
  709. def matches(self):
  710. if not (self.total_degree == 2 and self.dimension >= 3):
  711. return False
  712. if not self.homogeneous_order:
  713. return False
  714. # there may be Pow keys like x**2 or Mul keys like x*y
  715. return any(k.is_Mul for k in self.coeff) and self.homogeneous
  716. class GeneralSumOfSquares(DiophantineEquationType):
  717. r"""
  718. Representation of the diophantine equation
  719. `x_{1}^2 + x_{2}^2 + . . . + x_{n}^2 - k = 0`.
  720. Details
  721. =======
  722. When `n = 3` if `k = 4^a(8m + 7)` for some `a, m \in Z` then there will be
  723. no solutions. Refer [1]_ for more details.
  724. Examples
  725. ========
  726. >>> from sympy.solvers.diophantine.diophantine import GeneralSumOfSquares
  727. >>> from sympy.abc import a, b, c, d, e
  728. >>> GeneralSumOfSquares(a**2 + b**2 + c**2 + d**2 + e**2 - 2345).solve()
  729. {(15, 22, 22, 24, 24)}
  730. By default only 1 solution is returned. Use the `limit` keyword for more:
  731. >>> sorted(GeneralSumOfSquares(a**2 + b**2 + c**2 + d**2 + e**2 - 2345).solve(limit=3))
  732. [(15, 22, 22, 24, 24), (16, 19, 24, 24, 24), (16, 20, 22, 23, 26)]
  733. References
  734. ==========
  735. .. [1] Representing an integer as a sum of three squares, [online],
  736. Available:
  737. https://proofwiki.org/wiki/Integer_as_Sum_of_Three_Squares
  738. """
  739. name = 'general_sum_of_squares'
  740. def matches(self):
  741. if not (self.total_degree == 2 and self.dimension >= 3):
  742. return False
  743. if not self.homogeneous_order:
  744. return False
  745. if any(k.is_Mul for k in self.coeff):
  746. return False
  747. return all(self.coeff[k] == 1 for k in self.coeff if k != 1)
  748. def solve(self, parameters=None, limit=1):
  749. self.pre_solve(parameters)
  750. var = self.free_symbols
  751. k = -int(self.coeff[1])
  752. n = self.dimension
  753. result = DiophantineSolutionSet(var, parameters=self.parameters)
  754. if k < 0 or limit < 1:
  755. return result
  756. signs = [-1 if x.is_nonpositive else 1 for x in var]
  757. negs = signs.count(-1) != 0
  758. took = 0
  759. for t in sum_of_squares(k, n, zeros=True):
  760. if negs:
  761. result.add([signs[i]*j for i, j in enumerate(t)])
  762. else:
  763. result.add(t)
  764. took += 1
  765. if took == limit:
  766. break
  767. return result
  768. class GeneralPythagorean(DiophantineEquationType):
  769. """
  770. Representation of the general pythagorean equation,
  771. `a_{1}^2x_{1}^2 + a_{2}^2x_{2}^2 + . . . + a_{n}^2x_{n}^2 - a_{n + 1}^2x_{n + 1}^2 = 0`.
  772. Examples
  773. ========
  774. >>> from sympy.solvers.diophantine.diophantine import GeneralPythagorean
  775. >>> from sympy.abc import a, b, c, d, e, x, y, z, t
  776. >>> GeneralPythagorean(a**2 + b**2 + c**2 - d**2).solve()
  777. {(t_0**2 + t_1**2 - t_2**2, 2*t_0*t_2, 2*t_1*t_2, t_0**2 + t_1**2 + t_2**2)}
  778. >>> GeneralPythagorean(9*a**2 - 4*b**2 + 16*c**2 + 25*d**2 + e**2).solve(parameters=[x, y, z, t])
  779. {(-10*t**2 + 10*x**2 + 10*y**2 + 10*z**2, 15*t**2 + 15*x**2 + 15*y**2 + 15*z**2, 15*t*x, 12*t*y, 60*t*z)}
  780. """
  781. name = 'general_pythagorean'
  782. def matches(self):
  783. if not (self.total_degree == 2 and self.dimension >= 3):
  784. return False
  785. if not self.homogeneous_order:
  786. return False
  787. if any(k.is_Mul for k in self.coeff):
  788. return False
  789. if all(self.coeff[k] == 1 for k in self.coeff if k != 1):
  790. return False
  791. if not all(is_square(abs(self.coeff[k])) for k in self.coeff):
  792. return False
  793. # all but one has the same sign
  794. # e.g. 4*x**2 + y**2 - 4*z**2
  795. return abs(sum(sign(self.coeff[k]) for k in self.coeff)) == self.dimension - 2
  796. @property
  797. def n_parameters(self):
  798. return self.dimension - 1
  799. def solve(self, parameters=None, limit=1):
  800. self.pre_solve(parameters)
  801. coeff = self.coeff
  802. var = self.free_symbols
  803. n = self.dimension
  804. if sign(coeff[var[0] ** 2]) + sign(coeff[var[1] ** 2]) + sign(coeff[var[2] ** 2]) < 0:
  805. for key in coeff.keys():
  806. coeff[key] = -coeff[key]
  807. result = DiophantineSolutionSet(var, parameters=self.parameters)
  808. index = 0
  809. for i, v in enumerate(var):
  810. if sign(coeff[v ** 2]) == -1:
  811. index = i
  812. m = result.parameters
  813. ith = sum(m_i ** 2 for m_i in m)
  814. L = [ith - 2 * m[n - 2] ** 2]
  815. L.extend([2 * m[i] * m[n - 2] for i in range(n - 2)])
  816. sol = L[:index] + [ith] + L[index:]
  817. lcm = 1
  818. for i, v in enumerate(var):
  819. if i == index or (index > 0 and i == 0) or (index == 0 and i == 1):
  820. lcm = ilcm(lcm, sqrt(abs(coeff[v ** 2])))
  821. else:
  822. s = sqrt(coeff[v ** 2])
  823. lcm = ilcm(lcm, s if _odd(s) else s // 2)
  824. for i, v in enumerate(var):
  825. sol[i] = (lcm * sol[i]) / sqrt(abs(coeff[v ** 2]))
  826. result.add(sol)
  827. return result
  828. class CubicThue(DiophantineEquationType):
  829. """
  830. Representation of a cubic Thue diophantine equation.
  831. A cubic Thue diophantine equation is a polynomial of the form
  832. `f(x, y) = r` of degree 3, where `x` and `y` are integers
  833. and `r` is a rational number.
  834. No solver is currently implemented for this equation type.
  835. Examples
  836. ========
  837. >>> from sympy.abc import x, y
  838. >>> from sympy.solvers.diophantine.diophantine import CubicThue
  839. >>> c1 = CubicThue(x**3 + y**2 + 1)
  840. >>> c1.matches()
  841. True
  842. """
  843. name = 'cubic_thue'
  844. def matches(self):
  845. return self.total_degree == 3 and self.dimension == 2
  846. class GeneralSumOfEvenPowers(DiophantineEquationType):
  847. """
  848. Representation of the diophantine equation
  849. `x_{1}^e + x_{2}^e + . . . + x_{n}^e - k = 0`
  850. where `e` is an even, integer power.
  851. Examples
  852. ========
  853. >>> from sympy.solvers.diophantine.diophantine import GeneralSumOfEvenPowers
  854. >>> from sympy.abc import a, b
  855. >>> GeneralSumOfEvenPowers(a**4 + b**4 - (2**4 + 3**4)).solve()
  856. {(2, 3)}
  857. """
  858. name = 'general_sum_of_even_powers'
  859. def matches(self):
  860. if not self.total_degree > 3:
  861. return False
  862. if self.total_degree % 2 != 0:
  863. return False
  864. if not all(k.is_Pow and k.exp == self.total_degree for k in self.coeff if k != 1):
  865. return False
  866. return all(self.coeff[k] == 1 for k in self.coeff if k != 1)
  867. def solve(self, parameters=None, limit=1):
  868. self.pre_solve(parameters)
  869. var = self.free_symbols
  870. coeff = self.coeff
  871. p = None
  872. for q in coeff.keys():
  873. if q.is_Pow and coeff[q]:
  874. p = q.exp
  875. k = len(var)
  876. n = -coeff[1]
  877. result = DiophantineSolutionSet(var, parameters=self.parameters)
  878. if n < 0 or limit < 1:
  879. return result
  880. sign = [-1 if x.is_nonpositive else 1 for x in var]
  881. negs = sign.count(-1) != 0
  882. took = 0
  883. for t in power_representation(n, p, k):
  884. if negs:
  885. result.add([sign[i]*j for i, j in enumerate(t)])
  886. else:
  887. result.add(t)
  888. took += 1
  889. if took == limit:
  890. break
  891. return result
  892. # these types are known (but not necessarily handled)
  893. # note that order is important here (in the current solver state)
  894. all_diop_classes = [
  895. Linear,
  896. Univariate,
  897. BinaryQuadratic,
  898. InhomogeneousTernaryQuadratic,
  899. HomogeneousTernaryQuadraticNormal,
  900. HomogeneousTernaryQuadratic,
  901. InhomogeneousGeneralQuadratic,
  902. HomogeneousGeneralQuadratic,
  903. GeneralSumOfSquares,
  904. GeneralPythagorean,
  905. CubicThue,
  906. GeneralSumOfEvenPowers,
  907. ]
  908. diop_known = {diop_class.name for diop_class in all_diop_classes}
  909. def _remove_gcd(*x):
  910. try:
  911. g = igcd(*x)
  912. except ValueError:
  913. fx = list(filter(None, x))
  914. if len(fx) < 2:
  915. return x
  916. g = igcd(*[i.as_content_primitive()[0] for i in fx])
  917. except TypeError:
  918. raise TypeError('_remove_gcd(a,b,c) or _remove_gcd(*container)')
  919. if g == 1:
  920. return x
  921. return tuple([i//g for i in x])
  922. def _rational_pq(a, b):
  923. # return `(numer, denom)` for a/b; sign in numer and gcd removed
  924. return _remove_gcd(sign(b)*a, abs(b))
  925. def _nint_or_floor(p, q):
  926. # return nearest int to p/q; in case of tie return floor(p/q)
  927. w, r = divmod(p, q)
  928. if abs(r) <= abs(q)//2:
  929. return w
  930. return w + 1
  931. def _odd(i):
  932. return i % 2 != 0
  933. def _even(i):
  934. return i % 2 == 0
  935. def diophantine(eq, param=symbols("t", integer=True), syms=None,
  936. permute=False):
  937. """
  938. Simplify the solution procedure of diophantine equation ``eq`` by
  939. converting it into a product of terms which should equal zero.
  940. Explanation
  941. ===========
  942. For example, when solving, `x^2 - y^2 = 0` this is treated as
  943. `(x + y)(x - y) = 0` and `x + y = 0` and `x - y = 0` are solved
  944. independently and combined. Each term is solved by calling
  945. ``diop_solve()``. (Although it is possible to call ``diop_solve()``
  946. directly, one must be careful to pass an equation in the correct
  947. form and to interpret the output correctly; ``diophantine()`` is
  948. the public-facing function to use in general.)
  949. Output of ``diophantine()`` is a set of tuples. The elements of the
  950. tuple are the solutions for each variable in the equation and
  951. are arranged according to the alphabetic ordering of the variables.
  952. e.g. For an equation with two variables, `a` and `b`, the first
  953. element of the tuple is the solution for `a` and the second for `b`.
  954. Usage
  955. =====
  956. ``diophantine(eq, t, syms)``: Solve the diophantine
  957. equation ``eq``.
  958. ``t`` is the optional parameter to be used by ``diop_solve()``.
  959. ``syms`` is an optional list of symbols which determines the
  960. order of the elements in the returned tuple.
  961. By default, only the base solution is returned. If ``permute`` is set to
  962. True then permutations of the base solution and/or permutations of the
  963. signs of the values will be returned when applicable.
  964. Details
  965. =======
  966. ``eq`` should be an expression which is assumed to be zero.
  967. ``t`` is the parameter to be used in the solution.
  968. Examples
  969. ========
  970. >>> from sympy import diophantine
  971. >>> from sympy.abc import a, b
  972. >>> eq = a**4 + b**4 - (2**4 + 3**4)
  973. >>> diophantine(eq)
  974. {(2, 3)}
  975. >>> diophantine(eq, permute=True)
  976. {(-3, -2), (-3, 2), (-2, -3), (-2, 3), (2, -3), (2, 3), (3, -2), (3, 2)}
  977. >>> from sympy.abc import x, y, z
  978. >>> diophantine(x**2 - y**2)
  979. {(t_0, -t_0), (t_0, t_0)}
  980. >>> diophantine(x*(2*x + 3*y - z))
  981. {(0, n1, n2), (t_0, t_1, 2*t_0 + 3*t_1)}
  982. >>> diophantine(x**2 + 3*x*y + 4*x)
  983. {(0, n1), (-3*t_0 - 4, t_0)}
  984. See Also
  985. ========
  986. diop_solve
  987. sympy.utilities.iterables.permute_signs
  988. sympy.utilities.iterables.signed_permutations
  989. """
  990. eq = _sympify(eq)
  991. if isinstance(eq, Eq):
  992. eq = eq.lhs - eq.rhs
  993. try:
  994. var = list(eq.expand(force=True).free_symbols)
  995. var.sort(key=default_sort_key)
  996. if syms:
  997. if not is_sequence(syms):
  998. raise TypeError(
  999. 'syms should be given as a sequence, e.g. a list')
  1000. syms = [i for i in syms if i in var]
  1001. if syms != var:
  1002. dict_sym_index = dict(zip(syms, range(len(syms))))
  1003. return {tuple([t[dict_sym_index[i]] for i in var])
  1004. for t in diophantine(eq, param, permute=permute)}
  1005. n, d = eq.as_numer_denom()
  1006. if n.is_number:
  1007. return set()
  1008. if not d.is_number:
  1009. dsol = diophantine(d)
  1010. good = diophantine(n) - dsol
  1011. return {s for s in good if _mexpand(d.subs(zip(var, s)))}
  1012. eq = factor_terms(n)
  1013. assert not eq.is_number
  1014. eq = eq.as_independent(*var, as_Add=False)[1]
  1015. p = Poly(eq)
  1016. assert not any(g.is_number for g in p.gens)
  1017. eq = p.as_expr()
  1018. assert eq.is_polynomial()
  1019. except (GeneratorsNeeded, AssertionError):
  1020. raise TypeError(filldedent('''
  1021. Equation should be a polynomial with Rational coefficients.'''))
  1022. # permute only sign
  1023. do_permute_signs = False
  1024. # permute sign and values
  1025. do_permute_signs_var = False
  1026. # permute few signs
  1027. permute_few_signs = False
  1028. try:
  1029. # if we know that factoring should not be attempted, skip
  1030. # the factoring step
  1031. v, c, t = classify_diop(eq)
  1032. # check for permute sign
  1033. if permute:
  1034. len_var = len(v)
  1035. permute_signs_for = [
  1036. GeneralSumOfSquares.name,
  1037. GeneralSumOfEvenPowers.name]
  1038. permute_signs_check = [
  1039. HomogeneousTernaryQuadratic.name,
  1040. HomogeneousTernaryQuadraticNormal.name,
  1041. BinaryQuadratic.name]
  1042. if t in permute_signs_for:
  1043. do_permute_signs_var = True
  1044. elif t in permute_signs_check:
  1045. # if all the variables in eq have even powers
  1046. # then do_permute_sign = True
  1047. if len_var == 3:
  1048. var_mul = list(subsets(v, 2))
  1049. # here var_mul is like [(x, y), (x, z), (y, z)]
  1050. xy_coeff = True
  1051. x_coeff = True
  1052. var1_mul_var2 = (a[0]*a[1] for a in var_mul)
  1053. # if coeff(y*z), coeff(y*x), coeff(x*z) is not 0 then
  1054. # `xy_coeff` => True and do_permute_sign => False.
  1055. # Means no permuted solution.
  1056. for v1_mul_v2 in var1_mul_var2:
  1057. try:
  1058. coeff = c[v1_mul_v2]
  1059. except KeyError:
  1060. coeff = 0
  1061. xy_coeff = bool(xy_coeff) and bool(coeff)
  1062. var_mul = list(subsets(v, 1))
  1063. # here var_mul is like [(x,), (y, )]
  1064. for v1 in var_mul:
  1065. try:
  1066. coeff = c[v1[0]]
  1067. except KeyError:
  1068. coeff = 0
  1069. x_coeff = bool(x_coeff) and bool(coeff)
  1070. if not any((xy_coeff, x_coeff)):
  1071. # means only x**2, y**2, z**2, const is present
  1072. do_permute_signs = True
  1073. elif not x_coeff:
  1074. permute_few_signs = True
  1075. elif len_var == 2:
  1076. var_mul = list(subsets(v, 2))
  1077. # here var_mul is like [(x, y)]
  1078. xy_coeff = True
  1079. x_coeff = True
  1080. var1_mul_var2 = (x[0]*x[1] for x in var_mul)
  1081. for v1_mul_v2 in var1_mul_var2:
  1082. try:
  1083. coeff = c[v1_mul_v2]
  1084. except KeyError:
  1085. coeff = 0
  1086. xy_coeff = bool(xy_coeff) and bool(coeff)
  1087. var_mul = list(subsets(v, 1))
  1088. # here var_mul is like [(x,), (y, )]
  1089. for v1 in var_mul:
  1090. try:
  1091. coeff = c[v1[0]]
  1092. except KeyError:
  1093. coeff = 0
  1094. x_coeff = bool(x_coeff) and bool(coeff)
  1095. if not any((xy_coeff, x_coeff)):
  1096. # means only x**2, y**2 and const is present
  1097. # so we can get more soln by permuting this soln.
  1098. do_permute_signs = True
  1099. elif not x_coeff:
  1100. # when coeff(x), coeff(y) is not present then signs of
  1101. # x, y can be permuted such that their sign are same
  1102. # as sign of x*y.
  1103. # e.g 1. (x_val,y_val)=> (x_val,y_val), (-x_val,-y_val)
  1104. # 2. (-x_vall, y_val)=> (-x_val,y_val), (x_val,-y_val)
  1105. permute_few_signs = True
  1106. if t == 'general_sum_of_squares':
  1107. # trying to factor such expressions will sometimes hang
  1108. terms = [(eq, 1)]
  1109. else:
  1110. raise TypeError
  1111. except (TypeError, NotImplementedError):
  1112. fl = factor_list(eq)
  1113. if fl[0].is_Rational and fl[0] != 1:
  1114. return diophantine(eq/fl[0], param=param, syms=syms, permute=permute)
  1115. terms = fl[1]
  1116. sols = set()
  1117. for term in terms:
  1118. base, _ = term
  1119. var_t, _, eq_type = classify_diop(base, _dict=False)
  1120. _, base = signsimp(base, evaluate=False).as_coeff_Mul()
  1121. solution = diop_solve(base, param)
  1122. if eq_type in [
  1123. Linear.name,
  1124. HomogeneousTernaryQuadratic.name,
  1125. HomogeneousTernaryQuadraticNormal.name,
  1126. GeneralPythagorean.name]:
  1127. sols.add(merge_solution(var, var_t, solution))
  1128. elif eq_type in [
  1129. BinaryQuadratic.name,
  1130. GeneralSumOfSquares.name,
  1131. GeneralSumOfEvenPowers.name,
  1132. Univariate.name]:
  1133. sols.update(merge_solution(var, var_t, sol) for sol in solution)
  1134. else:
  1135. raise NotImplementedError('unhandled type: %s' % eq_type)
  1136. sols.discard(())
  1137. null = tuple([0]*len(var))
  1138. # if there is no solution, return trivial solution
  1139. if not sols and eq.subs(zip(var, null)).is_zero:
  1140. if all(check_assumptions(val, **s.assumptions0) is not False for val, s in zip(null, var)):
  1141. sols.add(null)
  1142. final_soln = set()
  1143. for sol in sols:
  1144. if all(int_valued(s) for s in sol):
  1145. if do_permute_signs:
  1146. permuted_sign = set(permute_signs(sol))
  1147. final_soln.update(permuted_sign)
  1148. elif permute_few_signs:
  1149. lst = list(permute_signs(sol))
  1150. lst = list(filter(lambda x: x[0]*x[1] == sol[1]*sol[0], lst))
  1151. permuted_sign = set(lst)
  1152. final_soln.update(permuted_sign)
  1153. elif do_permute_signs_var:
  1154. permuted_sign_var = set(signed_permutations(sol))
  1155. final_soln.update(permuted_sign_var)
  1156. else:
  1157. final_soln.add(sol)
  1158. else:
  1159. final_soln.add(sol)
  1160. return final_soln
  1161. def merge_solution(var, var_t, solution):
  1162. """
  1163. This is used to construct the full solution from the solutions of sub
  1164. equations.
  1165. Explanation
  1166. ===========
  1167. For example when solving the equation `(x - y)(x^2 + y^2 - z^2) = 0`,
  1168. solutions for each of the equations `x - y = 0` and `x^2 + y^2 - z^2` are
  1169. found independently. Solutions for `x - y = 0` are `(x, y) = (t, t)`. But
  1170. we should introduce a value for z when we output the solution for the
  1171. original equation. This function converts `(t, t)` into `(t, t, n_{1})`
  1172. where `n_{1}` is an integer parameter.
  1173. """
  1174. sol = []
  1175. if None in solution:
  1176. return ()
  1177. solution = iter(solution)
  1178. params = numbered_symbols("n", integer=True, start=1)
  1179. for v in var:
  1180. if v in var_t:
  1181. sol.append(next(solution))
  1182. else:
  1183. sol.append(next(params))
  1184. for val, symb in zip(sol, var):
  1185. if check_assumptions(val, **symb.assumptions0) is False:
  1186. return ()
  1187. return tuple(sol)
  1188. def _diop_solve(eq, params=None):
  1189. for diop_type in all_diop_classes:
  1190. if diop_type(eq).matches():
  1191. return diop_type(eq).solve(parameters=params)
  1192. def diop_solve(eq, param=symbols("t", integer=True)):
  1193. """
  1194. Solves the diophantine equation ``eq``.
  1195. Explanation
  1196. ===========
  1197. Unlike ``diophantine()``, factoring of ``eq`` is not attempted. Uses
  1198. ``classify_diop()`` to determine the type of the equation and calls
  1199. the appropriate solver function.
  1200. Use of ``diophantine()`` is recommended over other helper functions.
  1201. ``diop_solve()`` can return either a set or a tuple depending on the
  1202. nature of the equation. All non-trivial solutions are returned: assumptions
  1203. on symbols are ignored.
  1204. Usage
  1205. =====
  1206. ``diop_solve(eq, t)``: Solve diophantine equation, ``eq`` using ``t``
  1207. as a parameter if needed.
  1208. Details
  1209. =======
  1210. ``eq`` should be an expression which is assumed to be zero.
  1211. ``t`` is a parameter to be used in the solution.
  1212. Examples
  1213. ========
  1214. >>> from sympy.solvers.diophantine import diop_solve
  1215. >>> from sympy.abc import x, y, z, w
  1216. >>> diop_solve(2*x + 3*y - 5)
  1217. (3*t_0 - 5, 5 - 2*t_0)
  1218. >>> diop_solve(4*x + 3*y - 4*z + 5)
  1219. (t_0, 8*t_0 + 4*t_1 + 5, 7*t_0 + 3*t_1 + 5)
  1220. >>> diop_solve(x + 3*y - 4*z + w - 6)
  1221. (t_0, t_0 + t_1, 6*t_0 + 5*t_1 + 4*t_2 - 6, 5*t_0 + 4*t_1 + 3*t_2 - 6)
  1222. >>> diop_solve(x**2 + y**2 - 5)
  1223. {(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)}
  1224. See Also
  1225. ========
  1226. diophantine()
  1227. """
  1228. var, coeff, eq_type = classify_diop(eq, _dict=False)
  1229. if eq_type == Linear.name:
  1230. return diop_linear(eq, param)
  1231. elif eq_type == BinaryQuadratic.name:
  1232. return diop_quadratic(eq, param)
  1233. elif eq_type == HomogeneousTernaryQuadratic.name:
  1234. return diop_ternary_quadratic(eq, parameterize=True)
  1235. elif eq_type == HomogeneousTernaryQuadraticNormal.name:
  1236. return diop_ternary_quadratic_normal(eq, parameterize=True)
  1237. elif eq_type == GeneralPythagorean.name:
  1238. return diop_general_pythagorean(eq, param)
  1239. elif eq_type == Univariate.name:
  1240. return diop_univariate(eq)
  1241. elif eq_type == GeneralSumOfSquares.name:
  1242. return diop_general_sum_of_squares(eq, limit=S.Infinity)
  1243. elif eq_type == GeneralSumOfEvenPowers.name:
  1244. return diop_general_sum_of_even_powers(eq, limit=S.Infinity)
  1245. if eq_type is not None and eq_type not in diop_known:
  1246. raise ValueError(filldedent('''
  1247. Although this type of equation was identified, it is not yet
  1248. handled. It should, however, be listed in `diop_known` at the
  1249. top of this file. Developers should see comments at the end of
  1250. `classify_diop`.
  1251. ''')) # pragma: no cover
  1252. else:
  1253. raise NotImplementedError(
  1254. 'No solver has been written for %s.' % eq_type)
  1255. def classify_diop(eq, _dict=True):
  1256. # docstring supplied externally
  1257. matched = False
  1258. diop_type = None
  1259. for diop_class in all_diop_classes:
  1260. diop_type = diop_class(eq)
  1261. if diop_type.matches():
  1262. matched = True
  1263. break
  1264. if matched:
  1265. return diop_type.free_symbols, dict(diop_type.coeff) if _dict else diop_type.coeff, diop_type.name
  1266. # new diop type instructions
  1267. # --------------------------
  1268. # if this error raises and the equation *can* be classified,
  1269. # * it should be identified in the if-block above
  1270. # * the type should be added to the diop_known
  1271. # if a solver can be written for it,
  1272. # * a dedicated handler should be written (e.g. diop_linear)
  1273. # * it should be passed to that handler in diop_solve
  1274. raise NotImplementedError(filldedent('''
  1275. This equation is not yet recognized or else has not been
  1276. simplified sufficiently to put it in a form recognized by
  1277. diop_classify().'''))
  1278. classify_diop.func_doc = ( # type: ignore
  1279. '''
  1280. Helper routine used by diop_solve() to find information about ``eq``.
  1281. Explanation
  1282. ===========
  1283. Returns a tuple containing the type of the diophantine equation
  1284. along with the variables (free symbols) and their coefficients.
  1285. Variables are returned as a list and coefficients are returned
  1286. as a dict with the key being the respective term and the constant
  1287. term is keyed to 1. The type is one of the following:
  1288. * %s
  1289. Usage
  1290. =====
  1291. ``classify_diop(eq)``: Return variables, coefficients and type of the
  1292. ``eq``.
  1293. Details
  1294. =======
  1295. ``eq`` should be an expression which is assumed to be zero.
  1296. ``_dict`` is for internal use: when True (default) a dict is returned,
  1297. otherwise a defaultdict which supplies 0 for missing keys is returned.
  1298. Examples
  1299. ========
  1300. >>> from sympy.solvers.diophantine import classify_diop
  1301. >>> from sympy.abc import x, y, z, w, t
  1302. >>> classify_diop(4*x + 6*y - 4)
  1303. ([x, y], {1: -4, x: 4, y: 6}, 'linear')
  1304. >>> classify_diop(x + 3*y -4*z + 5)
  1305. ([x, y, z], {1: 5, x: 1, y: 3, z: -4}, 'linear')
  1306. >>> classify_diop(x**2 + y**2 - x*y + x + 5)
  1307. ([x, y], {1: 5, x: 1, x**2: 1, y**2: 1, x*y: -1}, 'binary_quadratic')
  1308. ''' % ('\n * '.join(sorted(diop_known))))
  1309. def diop_linear(eq, param=symbols("t", integer=True)):
  1310. """
  1311. Solves linear diophantine equations.
  1312. A linear diophantine equation is an equation of the form `a_{1}x_{1} +
  1313. a_{2}x_{2} + .. + a_{n}x_{n} = 0` where `a_{1}, a_{2}, ..a_{n}` are
  1314. integer constants and `x_{1}, x_{2}, ..x_{n}` are integer variables.
  1315. Usage
  1316. =====
  1317. ``diop_linear(eq)``: Returns a tuple containing solutions to the
  1318. diophantine equation ``eq``. Values in the tuple is arranged in the same
  1319. order as the sorted variables.
  1320. Details
  1321. =======
  1322. ``eq`` is a linear diophantine equation which is assumed to be zero.
  1323. ``param`` is the parameter to be used in the solution.
  1324. Examples
  1325. ========
  1326. >>> from sympy.solvers.diophantine.diophantine import diop_linear
  1327. >>> from sympy.abc import x, y, z
  1328. >>> diop_linear(2*x - 3*y - 5) # solves equation 2*x - 3*y - 5 == 0
  1329. (3*t_0 - 5, 2*t_0 - 5)
  1330. Here x = -3*t_0 - 5 and y = -2*t_0 - 5
  1331. >>> diop_linear(2*x - 3*y - 4*z -3)
  1332. (t_0, 2*t_0 + 4*t_1 + 3, -t_0 - 3*t_1 - 3)
  1333. See Also
  1334. ========
  1335. diop_quadratic(), diop_ternary_quadratic(), diop_general_pythagorean(),
  1336. diop_general_sum_of_squares()
  1337. """
  1338. var, coeff, diop_type = classify_diop(eq, _dict=False)
  1339. if diop_type == Linear.name:
  1340. parameters = None
  1341. if param is not None:
  1342. parameters = symbols('%s_0:%i' % (param, len(var)), integer=True)
  1343. result = Linear(eq).solve(parameters=parameters)
  1344. if param is None:
  1345. result = result(*[0]*len(result.parameters))
  1346. if len(result) > 0:
  1347. return list(result)[0]
  1348. else:
  1349. return tuple([None]*len(result.parameters))
  1350. def base_solution_linear(c, a, b, t=None):
  1351. """
  1352. Return the base solution for the linear equation, `ax + by = c`.
  1353. Explanation
  1354. ===========
  1355. Used by ``diop_linear()`` to find the base solution of a linear
  1356. Diophantine equation. If ``t`` is given then the parametrized solution is
  1357. returned.
  1358. Usage
  1359. =====
  1360. ``base_solution_linear(c, a, b, t)``: ``a``, ``b``, ``c`` are coefficients
  1361. in `ax + by = c` and ``t`` is the parameter to be used in the solution.
  1362. Examples
  1363. ========
  1364. >>> from sympy.solvers.diophantine.diophantine import base_solution_linear
  1365. >>> from sympy.abc import t
  1366. >>> base_solution_linear(5, 2, 3) # equation 2*x + 3*y = 5
  1367. (-5, 5)
  1368. >>> base_solution_linear(0, 5, 7) # equation 5*x + 7*y = 0
  1369. (0, 0)
  1370. >>> base_solution_linear(5, 2, 3, t) # equation 2*x + 3*y = 5
  1371. (3*t - 5, 5 - 2*t)
  1372. >>> base_solution_linear(0, 5, 7, t) # equation 5*x + 7*y = 0
  1373. (7*t, -5*t)
  1374. """
  1375. a, b, c = _remove_gcd(a, b, c)
  1376. if c == 0:
  1377. if t is None:
  1378. return (0, 0)
  1379. if b < 0:
  1380. t = -t
  1381. return (b*t, -a*t)
  1382. x0, y0, d = igcdex(abs(a), abs(b))
  1383. x0 *= sign(a)
  1384. y0 *= sign(b)
  1385. if c % d:
  1386. return (None, None)
  1387. if t is None:
  1388. return (c*x0, c*y0)
  1389. if b < 0:
  1390. t = -t
  1391. return (c*x0 + b*t, c*y0 - a*t)
  1392. def diop_univariate(eq):
  1393. """
  1394. Solves a univariate diophantine equations.
  1395. Explanation
  1396. ===========
  1397. A univariate diophantine equation is an equation of the form
  1398. `a_{0} + a_{1}x + a_{2}x^2 + .. + a_{n}x^n = 0` where `a_{1}, a_{2}, ..a_{n}` are
  1399. integer constants and `x` is an integer variable.
  1400. Usage
  1401. =====
  1402. ``diop_univariate(eq)``: Returns a set containing solutions to the
  1403. diophantine equation ``eq``.
  1404. Details
  1405. =======
  1406. ``eq`` is a univariate diophantine equation which is assumed to be zero.
  1407. Examples
  1408. ========
  1409. >>> from sympy.solvers.diophantine.diophantine import diop_univariate
  1410. >>> from sympy.abc import x
  1411. >>> diop_univariate((x - 2)*(x - 3)**2) # solves equation (x - 2)*(x - 3)**2 == 0
  1412. {(2,), (3,)}
  1413. """
  1414. var, coeff, diop_type = classify_diop(eq, _dict=False)
  1415. if diop_type == Univariate.name:
  1416. return {(int(i),) for i in solveset_real(
  1417. eq, var[0]).intersect(S.Integers)}
  1418. def divisible(a, b):
  1419. """
  1420. Returns `True` if ``a`` is divisible by ``b`` and `False` otherwise.
  1421. """
  1422. return not a % b
  1423. def diop_quadratic(eq, param=symbols("t", integer=True)):
  1424. """
  1425. Solves quadratic diophantine equations.
  1426. i.e. equations of the form `Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0`. Returns a
  1427. set containing the tuples `(x, y)` which contains the solutions. If there
  1428. are no solutions then `(None, None)` is returned.
  1429. Usage
  1430. =====
  1431. ``diop_quadratic(eq, param)``: ``eq`` is a quadratic binary diophantine
  1432. equation. ``param`` is used to indicate the parameter to be used in the
  1433. solution.
  1434. Details
  1435. =======
  1436. ``eq`` should be an expression which is assumed to be zero.
  1437. ``param`` is a parameter to be used in the solution.
  1438. Examples
  1439. ========
  1440. >>> from sympy.abc import x, y, t
  1441. >>> from sympy.solvers.diophantine.diophantine import diop_quadratic
  1442. >>> diop_quadratic(x**2 + y**2 + 2*x + 2*y + 2, t)
  1443. {(-1, -1)}
  1444. References
  1445. ==========
  1446. .. [1] Methods to solve Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0, [online],
  1447. Available: https://www.alpertron.com.ar/METHODS.HTM
  1448. .. [2] Solving the equation ax^2+ bxy + cy^2 + dx + ey + f= 0, [online],
  1449. Available: https://web.archive.org/web/20160323033111/http://www.jpr2718.org/ax2p.pdf
  1450. See Also
  1451. ========
  1452. diop_linear(), diop_ternary_quadratic(), diop_general_sum_of_squares(),
  1453. diop_general_pythagorean()
  1454. """
  1455. var, coeff, diop_type = classify_diop(eq, _dict=False)
  1456. if diop_type == BinaryQuadratic.name:
  1457. if param is not None:
  1458. parameters = [param, Symbol("u", integer=True)]
  1459. else:
  1460. parameters = None
  1461. return set(BinaryQuadratic(eq).solve(parameters=parameters))
  1462. def is_solution_quad(var, coeff, u, v):
  1463. """
  1464. Check whether `(u, v)` is solution to the quadratic binary diophantine
  1465. equation with the variable list ``var`` and coefficient dictionary
  1466. ``coeff``.
  1467. Not intended for use by normal users.
  1468. """
  1469. reps = dict(zip(var, (u, v)))
  1470. eq = Add(*[j*i.xreplace(reps) for i, j in coeff.items()])
  1471. return _mexpand(eq) == 0
  1472. def diop_DN(D, N, t=symbols("t", integer=True)):
  1473. """
  1474. Solves the equation `x^2 - Dy^2 = N`.
  1475. Explanation
  1476. ===========
  1477. Mainly concerned with the case `D > 0, D` is not a perfect square,
  1478. which is the same as the generalized Pell equation. The LMM
  1479. algorithm [1]_ is used to solve this equation.
  1480. Returns one solution tuple, (`x, y)` for each class of the solutions.
  1481. Other solutions of the class can be constructed according to the
  1482. values of ``D`` and ``N``.
  1483. Usage
  1484. =====
  1485. ``diop_DN(D, N, t)``: D and N are integers as in `x^2 - Dy^2 = N` and
  1486. ``t`` is the parameter to be used in the solutions.
  1487. Details
  1488. =======
  1489. ``D`` and ``N`` correspond to D and N in the equation.
  1490. ``t`` is the parameter to be used in the solutions.
  1491. Examples
  1492. ========
  1493. >>> from sympy.solvers.diophantine.diophantine import diop_DN
  1494. >>> diop_DN(13, -4) # Solves equation x**2 - 13*y**2 = -4
  1495. [(3, 1), (393, 109), (36, 10)]
  1496. The output can be interpreted as follows: There are three fundamental
  1497. solutions to the equation `x^2 - 13y^2 = -4` given by (3, 1), (393, 109)
  1498. and (36, 10). Each tuple is in the form (x, y), i.e. solution (3, 1) means
  1499. that `x = 3` and `y = 1`.
  1500. >>> diop_DN(986, 1) # Solves equation x**2 - 986*y**2 = 1
  1501. [(49299, 1570)]
  1502. See Also
  1503. ========
  1504. find_DN(), diop_bf_DN()
  1505. References
  1506. ==========
  1507. .. [1] Solving the generalized Pell equation x**2 - D*y**2 = N, John P.
  1508. Robertson, July 31, 2004, Pages 16 - 17. [online], Available:
  1509. https://web.archive.org/web/20160323033128/http://www.jpr2718.org/pell.pdf
  1510. """
  1511. if D < 0:
  1512. if N == 0:
  1513. return [(0, 0)]
  1514. if N < 0:
  1515. return []
  1516. # N > 0:
  1517. sol = []
  1518. for d in divisors(square_factor(N), generator=True):
  1519. for x, y in cornacchia(1, int(-D), int(N // d**2)):
  1520. sol.append((d*x, d*y))
  1521. if D == -1:
  1522. sol.append((d*y, d*x))
  1523. return sol
  1524. if D == 0:
  1525. if N < 0:
  1526. return []
  1527. if N == 0:
  1528. return [(0, t)]
  1529. sN, _exact = integer_nthroot(N, 2)
  1530. if _exact:
  1531. return [(sN, t)]
  1532. return []
  1533. # D > 0
  1534. sD, _exact = integer_nthroot(D, 2)
  1535. if _exact:
  1536. if N == 0:
  1537. return [(sD*t, t)]
  1538. sol = []
  1539. for y in range(floor(sign(N)*(N - 1)/(2*sD)) + 1):
  1540. try:
  1541. sq, _exact = integer_nthroot(D*y**2 + N, 2)
  1542. except ValueError:
  1543. _exact = False
  1544. if _exact:
  1545. sol.append((sq, y))
  1546. return sol
  1547. if 1 < N**2 < D:
  1548. # It is much faster to call `_special_diop_DN`.
  1549. return _special_diop_DN(D, N)
  1550. if N == 0:
  1551. return [(0, 0)]
  1552. sol = []
  1553. if abs(N) == 1:
  1554. pqa = PQa(0, 1, D)
  1555. *_, prev_B, prev_G = next(pqa)
  1556. for j, (*_, a, _, _B, _G) in enumerate(pqa):
  1557. if a == 2*sD:
  1558. break
  1559. prev_B, prev_G = _B, _G
  1560. if j % 2:
  1561. if N == 1:
  1562. sol.append((prev_G, prev_B))
  1563. return sol
  1564. if N == -1:
  1565. return [(prev_G, prev_B)]
  1566. for _ in range(j):
  1567. *_, _B, _G = next(pqa)
  1568. return [(_G, _B)]
  1569. for f in divisors(square_factor(N), generator=True):
  1570. m = N // f**2
  1571. am = abs(m)
  1572. for sqm in sqrt_mod(D, am, all_roots=True):
  1573. z = symmetric_residue(sqm, am)
  1574. pqa = PQa(z, am, D)
  1575. *_, prev_B, prev_G = next(pqa)
  1576. for _ in range(length(z, am, D) - 1):
  1577. _, q, *_, _B, _G = next(pqa)
  1578. if abs(q) == 1:
  1579. if prev_G**2 - D*prev_B**2 == m:
  1580. sol.append((f*prev_G, f*prev_B))
  1581. elif a := diop_DN(D, -1):
  1582. sol.append((f*(prev_G*a[0][0] + prev_B*D*a[0][1]),
  1583. f*(prev_G*a[0][1] + prev_B*a[0][0])))
  1584. break
  1585. prev_B, prev_G = _B, _G
  1586. return sol
  1587. def _special_diop_DN(D, N):
  1588. """
  1589. Solves the equation `x^2 - Dy^2 = N` for the special case where
  1590. `1 < N**2 < D` and `D` is not a perfect square.
  1591. It is better to call `diop_DN` rather than this function, as
  1592. the former checks the condition `1 < N**2 < D`, and calls the latter only
  1593. if appropriate.
  1594. Usage
  1595. =====
  1596. WARNING: Internal method. Do not call directly!
  1597. ``_special_diop_DN(D, N)``: D and N are integers as in `x^2 - Dy^2 = N`.
  1598. Details
  1599. =======
  1600. ``D`` and ``N`` correspond to D and N in the equation.
  1601. Examples
  1602. ========
  1603. >>> from sympy.solvers.diophantine.diophantine import _special_diop_DN
  1604. >>> _special_diop_DN(13, -3) # Solves equation x**2 - 13*y**2 = -3
  1605. [(7, 2), (137, 38)]
  1606. The output can be interpreted as follows: There are two fundamental
  1607. solutions to the equation `x^2 - 13y^2 = -3` given by (7, 2) and
  1608. (137, 38). Each tuple is in the form (x, y), i.e. solution (7, 2) means
  1609. that `x = 7` and `y = 2`.
  1610. >>> _special_diop_DN(2445, -20) # Solves equation x**2 - 2445*y**2 = -20
  1611. [(445, 9), (17625560, 356454), (698095554475, 14118073569)]
  1612. See Also
  1613. ========
  1614. diop_DN()
  1615. References
  1616. ==========
  1617. .. [1] Section 4.4.4 of the following book:
  1618. Quadratic Diophantine Equations, T. Andreescu and D. Andrica,
  1619. Springer, 2015.
  1620. """
  1621. # The following assertion was removed for efficiency, with the understanding
  1622. # that this method is not called directly. The parent method, `diop_DN`
  1623. # is responsible for performing the appropriate checks.
  1624. #
  1625. # assert (1 < N**2 < D) and (not integer_nthroot(D, 2)[1])
  1626. sqrt_D = isqrt(D)
  1627. F = {N // f**2: f for f in divisors(square_factor(abs(N)), generator=True)}
  1628. P = 0
  1629. Q = 1
  1630. G0, G1 = 0, 1
  1631. B0, B1 = 1, 0
  1632. solutions = []
  1633. while True:
  1634. for _ in range(2):
  1635. a = (P + sqrt_D) // Q
  1636. P = a*Q - P
  1637. Q = (D - P**2) // Q
  1638. G0, G1 = G1, a*G1 + G0
  1639. B0, B1 = B1, a*B1 + B0
  1640. if (s := G1**2 - D*B1**2) in F:
  1641. f = F[s]
  1642. solutions.append((f*G1, f*B1))
  1643. if Q == 1:
  1644. break
  1645. return solutions
  1646. def cornacchia(a:int, b:int, m:int) -> set[tuple[int, int]]:
  1647. r"""
  1648. Solves `ax^2 + by^2 = m` where `\gcd(a, b) = 1 = gcd(a, m)` and `a, b > 0`.
  1649. Explanation
  1650. ===========
  1651. Uses the algorithm due to Cornacchia. The method only finds primitive
  1652. solutions, i.e. ones with `\gcd(x, y) = 1`. So this method cannot be used to
  1653. find the solutions of `x^2 + y^2 = 20` since the only solution to former is
  1654. `(x, y) = (4, 2)` and it is not primitive. When `a = b`, only the
  1655. solutions with `x \leq y` are found. For more details, see the References.
  1656. Examples
  1657. ========
  1658. >>> from sympy.solvers.diophantine.diophantine import cornacchia
  1659. >>> cornacchia(2, 3, 35) # equation 2x**2 + 3y**2 = 35
  1660. {(2, 3), (4, 1)}
  1661. >>> cornacchia(1, 1, 25) # equation x**2 + y**2 = 25
  1662. {(4, 3)}
  1663. References
  1664. ===========
  1665. .. [1] A. Nitaj, "L'algorithme de Cornacchia"
  1666. .. [2] Solving the diophantine equation ax**2 + by**2 = m by Cornacchia's
  1667. method, [online], Available:
  1668. http://www.numbertheory.org/php/cornacchia.html
  1669. See Also
  1670. ========
  1671. sympy.utilities.iterables.signed_permutations
  1672. """
  1673. # Assume gcd(a, b) = gcd(a, m) = 1 and a, b > 0 but no error checking
  1674. sols = set()
  1675. if a + b > m:
  1676. # xy = 0 must hold if there exists a solution
  1677. if a == 1:
  1678. # y = 0
  1679. s, _exact = iroot(m // a, 2)
  1680. if _exact:
  1681. sols.add((int(s), 0))
  1682. if a == b:
  1683. # only keep one solution
  1684. return sols
  1685. if m % b == 0:
  1686. # x = 0
  1687. s, _exact = iroot(m // b, 2)
  1688. if _exact:
  1689. sols.add((0, int(s)))
  1690. return sols
  1691. # the original cornacchia
  1692. for t in sqrt_mod_iter(-b*invert(a, m), m):
  1693. if t < m // 2:
  1694. continue
  1695. u, r = m, t
  1696. while (m1 := m - a*r**2) <= 0:
  1697. u, r = r, u % r
  1698. m1, _r = divmod(m1, b)
  1699. if _r:
  1700. continue
  1701. s, _exact = iroot(m1, 2)
  1702. if _exact:
  1703. if a == b and r < s:
  1704. r, s = s, r
  1705. sols.add((int(r), int(s)))
  1706. return sols
  1707. def PQa(P_0, Q_0, D):
  1708. r"""
  1709. Returns useful information needed to solve the Pell equation.
  1710. Explanation
  1711. ===========
  1712. There are six sequences of integers defined related to the continued
  1713. fraction representation of `\\frac{P + \sqrt{D}}{Q}`, namely {`P_{i}`},
  1714. {`Q_{i}`}, {`a_{i}`},{`A_{i}`}, {`B_{i}`}, {`G_{i}`}. ``PQa()`` Returns
  1715. these values as a 6-tuple in the same order as mentioned above. Refer [1]_
  1716. for more detailed information.
  1717. Usage
  1718. =====
  1719. ``PQa(P_0, Q_0, D)``: ``P_0``, ``Q_0`` and ``D`` are integers corresponding
  1720. to `P_{0}`, `Q_{0}` and `D` in the continued fraction
  1721. `\\frac{P_{0} + \sqrt{D}}{Q_{0}}`.
  1722. Also it's assumed that `P_{0}^2 == D mod(|Q_{0}|)` and `D` is square free.
  1723. Examples
  1724. ========
  1725. >>> from sympy.solvers.diophantine.diophantine import PQa
  1726. >>> pqa = PQa(13, 4, 5) # (13 + sqrt(5))/4
  1727. >>> next(pqa) # (P_0, Q_0, a_0, A_0, B_0, G_0)
  1728. (13, 4, 3, 3, 1, -1)
  1729. >>> next(pqa) # (P_1, Q_1, a_1, A_1, B_1, G_1)
  1730. (-1, 1, 1, 4, 1, 3)
  1731. References
  1732. ==========
  1733. .. [1] Solving the generalized Pell equation x^2 - Dy^2 = N, John P.
  1734. Robertson, July 31, 2004, Pages 4 - 8. https://web.archive.org/web/20160323033128/http://www.jpr2718.org/pell.pdf
  1735. """
  1736. sqD = isqrt(D)
  1737. A2 = B1 = 0
  1738. A1 = B2 = 1
  1739. G1 = Q_0
  1740. G2 = -P_0
  1741. P_i = P_0
  1742. Q_i = Q_0
  1743. while True:
  1744. a_i = (P_i + sqD) // Q_i
  1745. A1, A2 = a_i*A1 + A2, A1
  1746. B1, B2 = a_i*B1 + B2, B1
  1747. G1, G2 = a_i*G1 + G2, G1
  1748. yield P_i, Q_i, a_i, A1, B1, G1
  1749. P_i = a_i*Q_i - P_i
  1750. Q_i = (D - P_i**2) // Q_i
  1751. def diop_bf_DN(D, N, t=symbols("t", integer=True)):
  1752. r"""
  1753. Uses brute force to solve the equation, `x^2 - Dy^2 = N`.
  1754. Explanation
  1755. ===========
  1756. Mainly concerned with the generalized Pell equation which is the case when
  1757. `D > 0, D` is not a perfect square. For more information on the case refer
  1758. [1]_. Let `(t, u)` be the minimal positive solution of the equation
  1759. `x^2 - Dy^2 = 1`. Then this method requires
  1760. `\sqrt{\\frac{\mid N \mid (t \pm 1)}{2D}}` to be small.
  1761. Usage
  1762. =====
  1763. ``diop_bf_DN(D, N, t)``: ``D`` and ``N`` are coefficients in
  1764. `x^2 - Dy^2 = N` and ``t`` is the parameter to be used in the solutions.
  1765. Details
  1766. =======
  1767. ``D`` and ``N`` correspond to D and N in the equation.
  1768. ``t`` is the parameter to be used in the solutions.
  1769. Examples
  1770. ========
  1771. >>> from sympy.solvers.diophantine.diophantine import diop_bf_DN
  1772. >>> diop_bf_DN(13, -4)
  1773. [(3, 1), (-3, 1), (36, 10)]
  1774. >>> diop_bf_DN(986, 1)
  1775. [(49299, 1570)]
  1776. See Also
  1777. ========
  1778. diop_DN()
  1779. References
  1780. ==========
  1781. .. [1] Solving the generalized Pell equation x**2 - D*y**2 = N, John P.
  1782. Robertson, July 31, 2004, Page 15. https://web.archive.org/web/20160323033128/http://www.jpr2718.org/pell.pdf
  1783. """
  1784. D = as_int(D)
  1785. N = as_int(N)
  1786. sol = []
  1787. a = diop_DN(D, 1)
  1788. u = a[0][0]
  1789. if N == 0:
  1790. if D < 0:
  1791. return [(0, 0)]
  1792. if D == 0:
  1793. return [(0, t)]
  1794. sD, _exact = integer_nthroot(D, 2)
  1795. if _exact:
  1796. return [(sD*t, t), (-sD*t, t)]
  1797. return [(0, 0)]
  1798. if abs(N) == 1:
  1799. return diop_DN(D, N)
  1800. if N > 1:
  1801. L1 = 0
  1802. L2 = integer_nthroot(int(N*(u - 1)/(2*D)), 2)[0] + 1
  1803. else: # N < -1
  1804. L1, _exact = integer_nthroot(-int(N/D), 2)
  1805. if not _exact:
  1806. L1 += 1
  1807. L2 = integer_nthroot(-int(N*(u + 1)/(2*D)), 2)[0] + 1
  1808. for y in range(L1, L2):
  1809. try:
  1810. x, _exact = integer_nthroot(N + D*y**2, 2)
  1811. except ValueError:
  1812. _exact = False
  1813. if _exact:
  1814. sol.append((x, y))
  1815. if not equivalent(x, y, -x, y, D, N):
  1816. sol.append((-x, y))
  1817. return sol
  1818. def equivalent(u, v, r, s, D, N):
  1819. """
  1820. Returns True if two solutions `(u, v)` and `(r, s)` of `x^2 - Dy^2 = N`
  1821. belongs to the same equivalence class and False otherwise.
  1822. Explanation
  1823. ===========
  1824. Two solutions `(u, v)` and `(r, s)` to the above equation fall to the same
  1825. equivalence class iff both `(ur - Dvs)` and `(us - vr)` are divisible by
  1826. `N`. See reference [1]_. No test is performed to test whether `(u, v)` and
  1827. `(r, s)` are actually solutions to the equation. User should take care of
  1828. this.
  1829. Usage
  1830. =====
  1831. ``equivalent(u, v, r, s, D, N)``: `(u, v)` and `(r, s)` are two solutions
  1832. of the equation `x^2 - Dy^2 = N` and all parameters involved are integers.
  1833. Examples
  1834. ========
  1835. >>> from sympy.solvers.diophantine.diophantine import equivalent
  1836. >>> equivalent(18, 5, -18, -5, 13, -1)
  1837. True
  1838. >>> equivalent(3, 1, -18, 393, 109, -4)
  1839. False
  1840. References
  1841. ==========
  1842. .. [1] Solving the generalized Pell equation x**2 - D*y**2 = N, John P.
  1843. Robertson, July 31, 2004, Page 12. https://web.archive.org/web/20160323033128/http://www.jpr2718.org/pell.pdf
  1844. """
  1845. return divisible(u*r - D*v*s, N) and divisible(u*s - v*r, N)
  1846. def length(P, Q, D):
  1847. r"""
  1848. Returns the (length of aperiodic part + length of periodic part) of
  1849. continued fraction representation of `\\frac{P + \sqrt{D}}{Q}`.
  1850. It is important to remember that this does NOT return the length of the
  1851. periodic part but the sum of the lengths of the two parts as mentioned
  1852. above.
  1853. Usage
  1854. =====
  1855. ``length(P, Q, D)``: ``P``, ``Q`` and ``D`` are integers corresponding to
  1856. the continued fraction `\\frac{P + \sqrt{D}}{Q}`.
  1857. Details
  1858. =======
  1859. ``P``, ``D`` and ``Q`` corresponds to P, D and Q in the continued fraction,
  1860. `\\frac{P + \sqrt{D}}{Q}`.
  1861. Examples
  1862. ========
  1863. >>> from sympy.solvers.diophantine.diophantine import length
  1864. >>> length(-2, 4, 5) # (-2 + sqrt(5))/4
  1865. 3
  1866. >>> length(-5, 4, 17) # (-5 + sqrt(17))/4
  1867. 4
  1868. See Also
  1869. ========
  1870. sympy.ntheory.continued_fraction.continued_fraction_periodic
  1871. """
  1872. from sympy.ntheory.continued_fraction import continued_fraction_periodic
  1873. v = continued_fraction_periodic(P, Q, D)
  1874. if isinstance(v[-1], list):
  1875. rpt = len(v[-1])
  1876. nonrpt = len(v) - 1
  1877. else:
  1878. rpt = 0
  1879. nonrpt = len(v)
  1880. return rpt + nonrpt
  1881. def transformation_to_DN(eq):
  1882. """
  1883. This function transforms general quadratic,
  1884. `ax^2 + bxy + cy^2 + dx + ey + f = 0`
  1885. to more easy to deal with `X^2 - DY^2 = N` form.
  1886. Explanation
  1887. ===========
  1888. This is used to solve the general quadratic equation by transforming it to
  1889. the latter form. Refer to [1]_ for more detailed information on the
  1890. transformation. This function returns a tuple (A, B) where A is a 2 X 2
  1891. matrix and B is a 2 X 1 matrix such that,
  1892. Transpose([x y]) = A * Transpose([X Y]) + B
  1893. Usage
  1894. =====
  1895. ``transformation_to_DN(eq)``: where ``eq`` is the quadratic to be
  1896. transformed.
  1897. Examples
  1898. ========
  1899. >>> from sympy.abc import x, y
  1900. >>> from sympy.solvers.diophantine.diophantine import transformation_to_DN
  1901. >>> A, B = transformation_to_DN(x**2 - 3*x*y - y**2 - 2*y + 1)
  1902. >>> A
  1903. Matrix([
  1904. [1/26, 3/26],
  1905. [ 0, 1/13]])
  1906. >>> B
  1907. Matrix([
  1908. [-6/13],
  1909. [-4/13]])
  1910. A, B returned are such that Transpose((x y)) = A * Transpose((X Y)) + B.
  1911. Substituting these values for `x` and `y` and a bit of simplifying work
  1912. will give an equation of the form `x^2 - Dy^2 = N`.
  1913. >>> from sympy.abc import X, Y
  1914. >>> from sympy import Matrix, simplify
  1915. >>> u = (A*Matrix([X, Y]) + B)[0] # Transformation for x
  1916. >>> u
  1917. X/26 + 3*Y/26 - 6/13
  1918. >>> v = (A*Matrix([X, Y]) + B)[1] # Transformation for y
  1919. >>> v
  1920. Y/13 - 4/13
  1921. Next we will substitute these formulas for `x` and `y` and do
  1922. ``simplify()``.
  1923. >>> eq = simplify((x**2 - 3*x*y - y**2 - 2*y + 1).subs(zip((x, y), (u, v))))
  1924. >>> eq
  1925. X**2/676 - Y**2/52 + 17/13
  1926. By multiplying the denominator appropriately, we can get a Pell equation
  1927. in the standard form.
  1928. >>> eq * 676
  1929. X**2 - 13*Y**2 + 884
  1930. If only the final equation is needed, ``find_DN()`` can be used.
  1931. See Also
  1932. ========
  1933. find_DN()
  1934. References
  1935. ==========
  1936. .. [1] Solving the equation ax^2 + bxy + cy^2 + dx + ey + f = 0,
  1937. John P.Robertson, May 8, 2003, Page 7 - 11.
  1938. https://web.archive.org/web/20160323033111/http://www.jpr2718.org/ax2p.pdf
  1939. """
  1940. var, coeff, diop_type = classify_diop(eq, _dict=False)
  1941. if diop_type == BinaryQuadratic.name:
  1942. return _transformation_to_DN(var, coeff)
  1943. def _transformation_to_DN(var, coeff):
  1944. x, y = var
  1945. a = coeff[x**2]
  1946. b = coeff[x*y]
  1947. c = coeff[y**2]
  1948. d = coeff[x]
  1949. e = coeff[y]
  1950. f = coeff[1]
  1951. a, b, c, d, e, f = [as_int(i) for i in _remove_gcd(a, b, c, d, e, f)]
  1952. X, Y = symbols("X, Y", integer=True)
  1953. if b:
  1954. B, C = _rational_pq(2*a, b)
  1955. A, T = _rational_pq(a, B**2)
  1956. # eq_1 = A*B*X**2 + B*(c*T - A*C**2)*Y**2 + d*T*X + (B*e*T - d*T*C)*Y + f*T*B
  1957. coeff = {X**2: A*B, X*Y: 0, Y**2: B*(c*T - A*C**2), X: d*T, Y: B*e*T - d*T*C, 1: f*T*B}
  1958. A_0, B_0 = _transformation_to_DN([X, Y], coeff)
  1959. return Matrix(2, 2, [S.One/B, -S(C)/B, 0, 1])*A_0, Matrix(2, 2, [S.One/B, -S(C)/B, 0, 1])*B_0
  1960. if d:
  1961. B, C = _rational_pq(2*a, d)
  1962. A, T = _rational_pq(a, B**2)
  1963. # eq_2 = A*X**2 + c*T*Y**2 + e*T*Y + f*T - A*C**2
  1964. coeff = {X**2: A, X*Y: 0, Y**2: c*T, X: 0, Y: e*T, 1: f*T - A*C**2}
  1965. A_0, B_0 = _transformation_to_DN([X, Y], coeff)
  1966. return Matrix(2, 2, [S.One/B, 0, 0, 1])*A_0, Matrix(2, 2, [S.One/B, 0, 0, 1])*B_0 + Matrix([-S(C)/B, 0])
  1967. if e:
  1968. B, C = _rational_pq(2*c, e)
  1969. A, T = _rational_pq(c, B**2)
  1970. # eq_3 = a*T*X**2 + A*Y**2 + f*T - A*C**2
  1971. coeff = {X**2: a*T, X*Y: 0, Y**2: A, X: 0, Y: 0, 1: f*T - A*C**2}
  1972. A_0, B_0 = _transformation_to_DN([X, Y], coeff)
  1973. return Matrix(2, 2, [1, 0, 0, S.One/B])*A_0, Matrix(2, 2, [1, 0, 0, S.One/B])*B_0 + Matrix([0, -S(C)/B])
  1974. # TODO: pre-simplification: Not necessary but may simplify
  1975. # the equation.
  1976. return Matrix(2, 2, [S.One/a, 0, 0, 1]), Matrix([0, 0])
  1977. def find_DN(eq):
  1978. """
  1979. This function returns a tuple, `(D, N)` of the simplified form,
  1980. `x^2 - Dy^2 = N`, corresponding to the general quadratic,
  1981. `ax^2 + bxy + cy^2 + dx + ey + f = 0`.
  1982. Solving the general quadratic is then equivalent to solving the equation
  1983. `X^2 - DY^2 = N` and transforming the solutions by using the transformation
  1984. matrices returned by ``transformation_to_DN()``.
  1985. Usage
  1986. =====
  1987. ``find_DN(eq)``: where ``eq`` is the quadratic to be transformed.
  1988. Examples
  1989. ========
  1990. >>> from sympy.abc import x, y
  1991. >>> from sympy.solvers.diophantine.diophantine import find_DN
  1992. >>> find_DN(x**2 - 3*x*y - y**2 - 2*y + 1)
  1993. (13, -884)
  1994. Interpretation of the output is that we get `X^2 -13Y^2 = -884` after
  1995. transforming `x^2 - 3xy - y^2 - 2y + 1` using the transformation returned
  1996. by ``transformation_to_DN()``.
  1997. See Also
  1998. ========
  1999. transformation_to_DN()
  2000. References
  2001. ==========
  2002. .. [1] Solving the equation ax^2 + bxy + cy^2 + dx + ey + f = 0,
  2003. John P.Robertson, May 8, 2003, Page 7 - 11.
  2004. https://web.archive.org/web/20160323033111/http://www.jpr2718.org/ax2p.pdf
  2005. """
  2006. var, coeff, diop_type = classify_diop(eq, _dict=False)
  2007. if diop_type == BinaryQuadratic.name:
  2008. return _find_DN(var, coeff)
  2009. def _find_DN(var, coeff):
  2010. x, y = var
  2011. X, Y = symbols("X, Y", integer=True)
  2012. A, B = _transformation_to_DN(var, coeff)
  2013. u = (A*Matrix([X, Y]) + B)[0]
  2014. v = (A*Matrix([X, Y]) + B)[1]
  2015. eq = x**2*coeff[x**2] + x*y*coeff[x*y] + y**2*coeff[y**2] + x*coeff[x] + y*coeff[y] + coeff[1]
  2016. simplified = _mexpand(eq.subs(zip((x, y), (u, v))))
  2017. coeff = simplified.as_coefficients_dict()
  2018. return -coeff[Y**2]/coeff[X**2], -coeff[1]/coeff[X**2]
  2019. def check_param(x, y, a, params):
  2020. """
  2021. If there is a number modulo ``a`` such that ``x`` and ``y`` are both
  2022. integers, then return a parametric representation for ``x`` and ``y``
  2023. else return (None, None).
  2024. Here ``x`` and ``y`` are functions of ``t``.
  2025. """
  2026. from sympy.simplify.simplify import clear_coefficients
  2027. if x.is_number and not x.is_Integer:
  2028. return DiophantineSolutionSet([x, y], parameters=params)
  2029. if y.is_number and not y.is_Integer:
  2030. return DiophantineSolutionSet([x, y], parameters=params)
  2031. m, n = symbols("m, n", integer=True)
  2032. c, p = (m*x + n*y).as_content_primitive()
  2033. if a % c.q:
  2034. return DiophantineSolutionSet([x, y], parameters=params)
  2035. # clear_coefficients(mx + b, R)[1] -> (R - b)/m
  2036. eq = clear_coefficients(x, m)[1] - clear_coefficients(y, n)[1]
  2037. junk, eq = eq.as_content_primitive()
  2038. return _diop_solve(eq, params=params)
  2039. def diop_ternary_quadratic(eq, parameterize=False):
  2040. """
  2041. Solves the general quadratic ternary form,
  2042. `ax^2 + by^2 + cz^2 + fxy + gyz + hxz = 0`.
  2043. Returns a tuple `(x, y, z)` which is a base solution for the above
  2044. equation. If there are no solutions, `(None, None, None)` is returned.
  2045. Usage
  2046. =====
  2047. ``diop_ternary_quadratic(eq)``: Return a tuple containing a basic solution
  2048. to ``eq``.
  2049. Details
  2050. =======
  2051. ``eq`` should be an homogeneous expression of degree two in three variables
  2052. and it is assumed to be zero.
  2053. Examples
  2054. ========
  2055. >>> from sympy.abc import x, y, z
  2056. >>> from sympy.solvers.diophantine.diophantine import diop_ternary_quadratic
  2057. >>> diop_ternary_quadratic(x**2 + 3*y**2 - z**2)
  2058. (1, 0, 1)
  2059. >>> diop_ternary_quadratic(4*x**2 + 5*y**2 - z**2)
  2060. (1, 0, 2)
  2061. >>> diop_ternary_quadratic(45*x**2 - 7*y**2 - 8*x*y - z**2)
  2062. (28, 45, 105)
  2063. >>> diop_ternary_quadratic(x**2 - 49*y**2 - z**2 + 13*z*y -8*x*y)
  2064. (9, 1, 5)
  2065. """
  2066. var, coeff, diop_type = classify_diop(eq, _dict=False)
  2067. if diop_type in (
  2068. HomogeneousTernaryQuadratic.name,
  2069. HomogeneousTernaryQuadraticNormal.name):
  2070. sol = _diop_ternary_quadratic(var, coeff)
  2071. if len(sol) > 0:
  2072. x_0, y_0, z_0 = list(sol)[0]
  2073. else:
  2074. x_0, y_0, z_0 = None, None, None
  2075. if parameterize:
  2076. return _parametrize_ternary_quadratic(
  2077. (x_0, y_0, z_0), var, coeff)
  2078. return x_0, y_0, z_0
  2079. def _diop_ternary_quadratic(_var, coeff):
  2080. eq = sum(i*coeff[i] for i in coeff)
  2081. if HomogeneousTernaryQuadratic(eq).matches():
  2082. return HomogeneousTernaryQuadratic(eq, free_symbols=_var).solve()
  2083. elif HomogeneousTernaryQuadraticNormal(eq).matches():
  2084. return HomogeneousTernaryQuadraticNormal(eq, free_symbols=_var).solve()
  2085. def transformation_to_normal(eq):
  2086. """
  2087. Returns the transformation Matrix that converts a general ternary
  2088. quadratic equation ``eq`` (`ax^2 + by^2 + cz^2 + dxy + eyz + fxz`)
  2089. to a form without cross terms: `ax^2 + by^2 + cz^2 = 0`. This is
  2090. not used in solving ternary quadratics; it is only implemented for
  2091. the sake of completeness.
  2092. """
  2093. var, coeff, diop_type = classify_diop(eq, _dict=False)
  2094. if diop_type in (
  2095. "homogeneous_ternary_quadratic",
  2096. "homogeneous_ternary_quadratic_normal"):
  2097. return _transformation_to_normal(var, coeff)
  2098. def _transformation_to_normal(var, coeff):
  2099. _var = list(var) # copy
  2100. x, y, z = var
  2101. if not any(coeff[i**2] for i in var):
  2102. # https://math.stackexchange.com/questions/448051/transform-quadratic-ternary-form-to-normal-form/448065#448065
  2103. a = coeff[x*y]
  2104. b = coeff[y*z]
  2105. c = coeff[x*z]
  2106. swap = False
  2107. if not a: # b can't be 0 or else there aren't 3 vars
  2108. swap = True
  2109. a, b = b, a
  2110. T = Matrix(((1, 1, -b/a), (1, -1, -c/a), (0, 0, 1)))
  2111. if swap:
  2112. T.row_swap(0, 1)
  2113. T.col_swap(0, 1)
  2114. return T
  2115. if coeff[x**2] == 0:
  2116. # If the coefficient of x is zero change the variables
  2117. if coeff[y**2] == 0:
  2118. _var[0], _var[2] = var[2], var[0]
  2119. T = _transformation_to_normal(_var, coeff)
  2120. T.row_swap(0, 2)
  2121. T.col_swap(0, 2)
  2122. return T
  2123. _var[0], _var[1] = var[1], var[0]
  2124. T = _transformation_to_normal(_var, coeff)
  2125. T.row_swap(0, 1)
  2126. T.col_swap(0, 1)
  2127. return T
  2128. # Apply the transformation x --> X - (B*Y + C*Z)/(2*A)
  2129. if coeff[x*y] != 0 or coeff[x*z] != 0:
  2130. A = coeff[x**2]
  2131. B = coeff[x*y]
  2132. C = coeff[x*z]
  2133. D = coeff[y**2]
  2134. E = coeff[y*z]
  2135. F = coeff[z**2]
  2136. _coeff = {}
  2137. _coeff[x**2] = 4*A**2
  2138. _coeff[y**2] = 4*A*D - B**2
  2139. _coeff[z**2] = 4*A*F - C**2
  2140. _coeff[y*z] = 4*A*E - 2*B*C
  2141. _coeff[x*y] = 0
  2142. _coeff[x*z] = 0
  2143. T_0 = _transformation_to_normal(_var, _coeff)
  2144. return Matrix(3, 3, [1, S(-B)/(2*A), S(-C)/(2*A), 0, 1, 0, 0, 0, 1])*T_0
  2145. elif coeff[y*z] != 0:
  2146. if coeff[y**2] == 0:
  2147. if coeff[z**2] == 0:
  2148. # Equations of the form A*x**2 + E*yz = 0.
  2149. # Apply transformation y -> Y + Z ans z -> Y - Z
  2150. return Matrix(3, 3, [1, 0, 0, 0, 1, 1, 0, 1, -1])
  2151. # Ax**2 + E*y*z + F*z**2 = 0
  2152. _var[0], _var[2] = var[2], var[0]
  2153. T = _transformation_to_normal(_var, coeff)
  2154. T.row_swap(0, 2)
  2155. T.col_swap(0, 2)
  2156. return T
  2157. # A*x**2 + D*y**2 + E*y*z + F*z**2 = 0, F may be zero
  2158. _var[0], _var[1] = var[1], var[0]
  2159. T = _transformation_to_normal(_var, coeff)
  2160. T.row_swap(0, 1)
  2161. T.col_swap(0, 1)
  2162. return T
  2163. return Matrix.eye(3)
  2164. def parametrize_ternary_quadratic(eq):
  2165. """
  2166. Returns the parametrized general solution for the ternary quadratic
  2167. equation ``eq`` which has the form
  2168. `ax^2 + by^2 + cz^2 + fxy + gyz + hxz = 0`.
  2169. Examples
  2170. ========
  2171. >>> from sympy import Tuple, ordered
  2172. >>> from sympy.abc import x, y, z
  2173. >>> from sympy.solvers.diophantine.diophantine import parametrize_ternary_quadratic
  2174. The parametrized solution may be returned with three parameters:
  2175. >>> parametrize_ternary_quadratic(2*x**2 + y**2 - 2*z**2)
  2176. (p**2 - 2*q**2, -2*p**2 + 4*p*q - 4*p*r - 4*q**2, p**2 - 4*p*q + 2*q**2 - 4*q*r)
  2177. There might also be only two parameters:
  2178. >>> parametrize_ternary_quadratic(4*x**2 + 2*y**2 - 3*z**2)
  2179. (2*p**2 - 3*q**2, -4*p**2 + 12*p*q - 6*q**2, 4*p**2 - 8*p*q + 6*q**2)
  2180. Notes
  2181. =====
  2182. Consider ``p`` and ``q`` in the previous 2-parameter
  2183. solution and observe that more than one solution can be represented
  2184. by a given pair of parameters. If `p` and ``q`` are not coprime, this is
  2185. trivially true since the common factor will also be a common factor of the
  2186. solution values. But it may also be true even when ``p`` and
  2187. ``q`` are coprime:
  2188. >>> sol = Tuple(*_)
  2189. >>> p, q = ordered(sol.free_symbols)
  2190. >>> sol.subs([(p, 3), (q, 2)])
  2191. (6, 12, 12)
  2192. >>> sol.subs([(q, 1), (p, 1)])
  2193. (-1, 2, 2)
  2194. >>> sol.subs([(q, 0), (p, 1)])
  2195. (2, -4, 4)
  2196. >>> sol.subs([(q, 1), (p, 0)])
  2197. (-3, -6, 6)
  2198. Except for sign and a common factor, these are equivalent to
  2199. the solution of (1, 2, 2).
  2200. References
  2201. ==========
  2202. .. [1] The algorithmic resolution of Diophantine equations, Nigel P. Smart,
  2203. London Mathematical Society Student Texts 41, Cambridge University
  2204. Press, Cambridge, 1998.
  2205. """
  2206. var, coeff, diop_type = classify_diop(eq, _dict=False)
  2207. if diop_type in (
  2208. "homogeneous_ternary_quadratic",
  2209. "homogeneous_ternary_quadratic_normal"):
  2210. x_0, y_0, z_0 = list(_diop_ternary_quadratic(var, coeff))[0]
  2211. return _parametrize_ternary_quadratic(
  2212. (x_0, y_0, z_0), var, coeff)
  2213. def _parametrize_ternary_quadratic(solution, _var, coeff):
  2214. # called for a*x**2 + b*y**2 + c*z**2 + d*x*y + e*y*z + f*x*z = 0
  2215. assert 1 not in coeff
  2216. x_0, y_0, z_0 = solution
  2217. v = list(_var) # copy
  2218. if x_0 is None:
  2219. return (None, None, None)
  2220. if solution.count(0) >= 2:
  2221. # if there are 2 zeros the equation reduces
  2222. # to k*X**2 == 0 where X is x, y, or z so X must
  2223. # be zero, too. So there is only the trivial
  2224. # solution.
  2225. return (None, None, None)
  2226. if x_0 == 0:
  2227. v[0], v[1] = v[1], v[0]
  2228. y_p, x_p, z_p = _parametrize_ternary_quadratic(
  2229. (y_0, x_0, z_0), v, coeff)
  2230. return x_p, y_p, z_p
  2231. x, y, z = v
  2232. r, p, q = symbols("r, p, q", integer=True)
  2233. eq = sum(k*v for k, v in coeff.items())
  2234. eq_1 = _mexpand(eq.subs(zip(
  2235. (x, y, z), (r*x_0, r*y_0 + p, r*z_0 + q))))
  2236. A, B = eq_1.as_independent(r, as_Add=True)
  2237. x = A*x_0
  2238. y = (A*y_0 - _mexpand(B/r*p))
  2239. z = (A*z_0 - _mexpand(B/r*q))
  2240. return _remove_gcd(x, y, z)
  2241. def diop_ternary_quadratic_normal(eq, parameterize=False):
  2242. """
  2243. Solves the quadratic ternary diophantine equation,
  2244. `ax^2 + by^2 + cz^2 = 0`.
  2245. Explanation
  2246. ===========
  2247. Here the coefficients `a`, `b`, and `c` should be non zero. Otherwise the
  2248. equation will be a quadratic binary or univariate equation. If solvable,
  2249. returns a tuple `(x, y, z)` that satisfies the given equation. If the
  2250. equation does not have integer solutions, `(None, None, None)` is returned.
  2251. Usage
  2252. =====
  2253. ``diop_ternary_quadratic_normal(eq)``: where ``eq`` is an equation of the form
  2254. `ax^2 + by^2 + cz^2 = 0`.
  2255. Examples
  2256. ========
  2257. >>> from sympy.abc import x, y, z
  2258. >>> from sympy.solvers.diophantine.diophantine import diop_ternary_quadratic_normal
  2259. >>> diop_ternary_quadratic_normal(x**2 + 3*y**2 - z**2)
  2260. (1, 0, 1)
  2261. >>> diop_ternary_quadratic_normal(4*x**2 + 5*y**2 - z**2)
  2262. (1, 0, 2)
  2263. >>> diop_ternary_quadratic_normal(34*x**2 - 3*y**2 - 301*z**2)
  2264. (4, 9, 1)
  2265. """
  2266. var, coeff, diop_type = classify_diop(eq, _dict=False)
  2267. if diop_type == HomogeneousTernaryQuadraticNormal.name:
  2268. sol = _diop_ternary_quadratic_normal(var, coeff)
  2269. if len(sol) > 0:
  2270. x_0, y_0, z_0 = list(sol)[0]
  2271. else:
  2272. x_0, y_0, z_0 = None, None, None
  2273. if parameterize:
  2274. return _parametrize_ternary_quadratic(
  2275. (x_0, y_0, z_0), var, coeff)
  2276. return x_0, y_0, z_0
  2277. def _diop_ternary_quadratic_normal(var, coeff):
  2278. eq = sum(i * coeff[i] for i in coeff)
  2279. return HomogeneousTernaryQuadraticNormal(eq, free_symbols=var).solve()
  2280. def sqf_normal(a, b, c, steps=False):
  2281. """
  2282. Return `a', b', c'`, the coefficients of the square-free normal
  2283. form of `ax^2 + by^2 + cz^2 = 0`, where `a', b', c'` are pairwise
  2284. prime. If `steps` is True then also return three tuples:
  2285. `sq`, `sqf`, and `(a', b', c')` where `sq` contains the square
  2286. factors of `a`, `b` and `c` after removing the `gcd(a, b, c)`;
  2287. `sqf` contains the values of `a`, `b` and `c` after removing
  2288. both the `gcd(a, b, c)` and the square factors.
  2289. The solutions for `ax^2 + by^2 + cz^2 = 0` can be
  2290. recovered from the solutions of `a'x^2 + b'y^2 + c'z^2 = 0`.
  2291. Examples
  2292. ========
  2293. >>> from sympy.solvers.diophantine.diophantine import sqf_normal
  2294. >>> sqf_normal(2 * 3**2 * 5, 2 * 5 * 11, 2 * 7**2 * 11)
  2295. (11, 1, 5)
  2296. >>> sqf_normal(2 * 3**2 * 5, 2 * 5 * 11, 2 * 7**2 * 11, True)
  2297. ((3, 1, 7), (5, 55, 11), (11, 1, 5))
  2298. References
  2299. ==========
  2300. .. [1] Legendre's Theorem, Legrange's Descent,
  2301. https://public.csusm.edu/aitken_html/notes/legendre.pdf
  2302. See Also
  2303. ========
  2304. reconstruct()
  2305. """
  2306. ABC = _remove_gcd(a, b, c)
  2307. sq = tuple(square_factor(i) for i in ABC)
  2308. sqf = A, B, C = tuple([i//j**2 for i,j in zip(ABC, sq)])
  2309. pc = igcd(A, B)
  2310. A /= pc
  2311. B /= pc
  2312. pa = igcd(B, C)
  2313. B /= pa
  2314. C /= pa
  2315. pb = igcd(A, C)
  2316. A /= pb
  2317. B /= pb
  2318. A *= pa
  2319. B *= pb
  2320. C *= pc
  2321. if steps:
  2322. return (sq, sqf, (A, B, C))
  2323. else:
  2324. return A, B, C
  2325. def square_factor(a):
  2326. r"""
  2327. Returns an integer `c` s.t. `a = c^2k, \ c,k \in Z`. Here `k` is square
  2328. free. `a` can be given as an integer or a dictionary of factors.
  2329. Examples
  2330. ========
  2331. >>> from sympy.solvers.diophantine.diophantine import square_factor
  2332. >>> square_factor(24)
  2333. 2
  2334. >>> square_factor(-36*3)
  2335. 6
  2336. >>> square_factor(1)
  2337. 1
  2338. >>> square_factor({3: 2, 2: 1, -1: 1}) # -18
  2339. 3
  2340. See Also
  2341. ========
  2342. sympy.ntheory.factor_.core
  2343. """
  2344. f = a if isinstance(a, dict) else factorint(a)
  2345. return Mul(*[p**(e//2) for p, e in f.items()])
  2346. def reconstruct(A, B, z):
  2347. """
  2348. Reconstruct the `z` value of an equivalent solution of `ax^2 + by^2 + cz^2`
  2349. from the `z` value of a solution of the square-free normal form of the
  2350. equation, `a'*x^2 + b'*y^2 + c'*z^2`, where `a'`, `b'` and `c'` are square
  2351. free and `gcd(a', b', c') == 1`.
  2352. """
  2353. f = factorint(igcd(A, B))
  2354. for p, e in f.items():
  2355. if e != 1:
  2356. raise ValueError('a and b should be square-free')
  2357. z *= p
  2358. return z
  2359. def ldescent(A, B):
  2360. """
  2361. Return a non-trivial solution to `w^2 = Ax^2 + By^2` using
  2362. Lagrange's method; return None if there is no such solution.
  2363. Parameters
  2364. ==========
  2365. A : Integer
  2366. B : Integer
  2367. non-zero integer
  2368. Returns
  2369. =======
  2370. (int, int, int) | None : a tuple `(w_0, x_0, y_0)` which is a solution to the above equation.
  2371. Examples
  2372. ========
  2373. >>> from sympy.solvers.diophantine.diophantine import ldescent
  2374. >>> ldescent(1, 1) # w^2 = x^2 + y^2
  2375. (1, 1, 0)
  2376. >>> ldescent(4, -7) # w^2 = 4x^2 - 7y^2
  2377. (2, -1, 0)
  2378. This means that `x = -1, y = 0` and `w = 2` is a solution to the equation
  2379. `w^2 = 4x^2 - 7y^2`
  2380. >>> ldescent(5, -1) # w^2 = 5x^2 - y^2
  2381. (2, 1, -1)
  2382. References
  2383. ==========
  2384. .. [1] The algorithmic resolution of Diophantine equations, Nigel P. Smart,
  2385. London Mathematical Society Student Texts 41, Cambridge University
  2386. Press, Cambridge, 1998.
  2387. .. [2] Cremona, J. E., Rusin, D. (2003). Efficient Solution of Rational Conics.
  2388. Mathematics of Computation, 72(243), 1417-1441.
  2389. https://doi.org/10.1090/S0025-5718-02-01480-1
  2390. """
  2391. if A == 0 or B == 0:
  2392. raise ValueError("A and B must be non-zero integers")
  2393. if abs(A) > abs(B):
  2394. w, y, x = ldescent(B, A)
  2395. return w, x, y
  2396. if A == 1:
  2397. return (1, 1, 0)
  2398. if B == 1:
  2399. return (1, 0, 1)
  2400. if B == -1: # and A == -1
  2401. return
  2402. r = sqrt_mod(A, B)
  2403. if r is None:
  2404. return
  2405. Q = (r**2 - A) // B
  2406. if Q == 0:
  2407. return r, -1, 0
  2408. for i in divisors(Q):
  2409. d, _exact = integer_nthroot(abs(Q) // i, 2)
  2410. if _exact:
  2411. B_0 = sign(Q)*i
  2412. W, X, Y = ldescent(A, B_0)
  2413. return _remove_gcd(-A*X + r*W, r*X - W, Y*B_0*d)
  2414. def descent(A, B):
  2415. """
  2416. Returns a non-trivial solution, (x, y, z), to `x^2 = Ay^2 + Bz^2`
  2417. using Lagrange's descent method with lattice-reduction. `A` and `B`
  2418. are assumed to be valid for such a solution to exist.
  2419. This is faster than the normal Lagrange's descent algorithm because
  2420. the Gaussian reduction is used.
  2421. Examples
  2422. ========
  2423. >>> from sympy.solvers.diophantine.diophantine import descent
  2424. >>> descent(3, 1) # x**2 = 3*y**2 + z**2
  2425. (1, 0, 1)
  2426. `(x, y, z) = (1, 0, 1)` is a solution to the above equation.
  2427. >>> descent(41, -113)
  2428. (-16, -3, 1)
  2429. References
  2430. ==========
  2431. .. [1] Cremona, J. E., Rusin, D. (2003). Efficient Solution of Rational Conics.
  2432. Mathematics of Computation, 72(243), 1417-1441.
  2433. https://doi.org/10.1090/S0025-5718-02-01480-1
  2434. """
  2435. if abs(A) > abs(B):
  2436. x, y, z = descent(B, A)
  2437. return x, z, y
  2438. if B == 1:
  2439. return (1, 0, 1)
  2440. if A == 1:
  2441. return (1, 1, 0)
  2442. if B == -A:
  2443. return (0, 1, 1)
  2444. if B == A:
  2445. x, z, y = descent(-1, A)
  2446. return (A*y, z, x)
  2447. w = sqrt_mod(A, B)
  2448. x_0, z_0 = gaussian_reduce(w, A, B)
  2449. t = (x_0**2 - A*z_0**2) // B
  2450. t_2 = square_factor(t)
  2451. t_1 = t // t_2**2
  2452. x_1, z_1, y_1 = descent(A, t_1)
  2453. return _remove_gcd(x_0*x_1 + A*z_0*z_1, z_0*x_1 + x_0*z_1, t_1*t_2*y_1)
  2454. def gaussian_reduce(w:int, a:int, b:int) -> tuple[int, int]:
  2455. r"""
  2456. Returns a reduced solution `(x, z)` to the congruence
  2457. `X^2 - aZ^2 \equiv 0 \pmod{b}` so that `x^2 + |a|z^2` is as small as possible.
  2458. Here ``w`` is a solution of the congruence `x^2 \equiv a \pmod{b}`.
  2459. This function is intended to be used only for ``descent()``.
  2460. Explanation
  2461. ===========
  2462. The Gaussian reduction can find the shortest vector for any norm.
  2463. So we define the special norm for the vectors `u = (u_1, u_2)` and `v = (v_1, v_2)` as follows.
  2464. .. math ::
  2465. u \cdot v := (wu_1 + bu_2)(wv_1 + bv_2) + |a|u_1v_1
  2466. Note that, given the mapping `f: (u_1, u_2) \to (wu_1 + bu_2, u_1)`,
  2467. `f((u_1,u_2))` is the solution to `X^2 - aZ^2 \equiv 0 \pmod{b}`.
  2468. In other words, finding the shortest vector in this norm will yield a solution with smaller `X^2 + |a|Z^2`.
  2469. The algorithm starts from basis vectors `(0, 1)` and `(1, 0)`
  2470. (corresponding to solutions `(b, 0)` and `(w, 1)`, respectively) and finds the shortest vector.
  2471. The shortest vector does not necessarily correspond to the smallest solution,
  2472. but since ``descent()`` only wants the smallest possible solution, it is sufficient.
  2473. Parameters
  2474. ==========
  2475. w : int
  2476. ``w`` s.t. `w^2 \equiv a \pmod{b}`
  2477. a : int
  2478. square-free nonzero integer
  2479. b : int
  2480. square-free nonzero integer
  2481. Examples
  2482. ========
  2483. >>> from sympy.solvers.diophantine.diophantine import gaussian_reduce
  2484. >>> from sympy.ntheory.residue_ntheory import sqrt_mod
  2485. >>> a, b = 19, 101
  2486. >>> gaussian_reduce(sqrt_mod(a, b), a, b) # 1**2 - 19*(-4)**2 = -303
  2487. (1, -4)
  2488. >>> a, b = 11, 14
  2489. >>> x, z = gaussian_reduce(sqrt_mod(a, b), a, b)
  2490. >>> (x**2 - a*z**2) % b == 0
  2491. True
  2492. It does not always return the smallest solution.
  2493. >>> a, b = 6, 95
  2494. >>> min_x, min_z = 1, 4
  2495. >>> x, z = gaussian_reduce(sqrt_mod(a, b), a, b)
  2496. >>> (x**2 - a*z**2) % b == 0 and (min_x**2 - a*min_z**2) % b == 0
  2497. True
  2498. >>> min_x**2 + abs(a)*min_z**2 < x**2 + abs(a)*z**2
  2499. True
  2500. References
  2501. ==========
  2502. .. [1] Gaussian lattice Reduction [online]. Available:
  2503. https://web.archive.org/web/20201021115213/http://home.ie.cuhk.edu.hk/~wkshum/wordpress/?p=404
  2504. .. [2] Cremona, J. E., Rusin, D. (2003). Efficient Solution of Rational Conics.
  2505. Mathematics of Computation, 72(243), 1417-1441.
  2506. https://doi.org/10.1090/S0025-5718-02-01480-1
  2507. """
  2508. a = abs(a)
  2509. def _dot(u, v):
  2510. return u[0]*v[0] + a*u[1]*v[1]
  2511. u = (b, 0)
  2512. v = (w, 1) if b*w >= 0 else (-w, -1)
  2513. # i.e., _dot(u, v) >= 0
  2514. if b**2 < w**2 + a:
  2515. u, v = v, u
  2516. # i.e., norm(u) >= norm(v), where norm(u) := sqrt(_dot(u, u))
  2517. while _dot(u, u) > (dv := _dot(v, v)):
  2518. k = _dot(u, v) // dv
  2519. u, v = v, (u[0] - k*v[0], u[1] - k*v[1])
  2520. c = (v[0] - u[0], v[1] - u[1])
  2521. if _dot(c, c) <= _dot(u, u) <= 2*_dot(u, v):
  2522. return c
  2523. return u
  2524. def holzer(x, y, z, a, b, c):
  2525. r"""
  2526. Simplify the solution `(x, y, z)` of the equation
  2527. `ax^2 + by^2 = cz^2` with `a, b, c > 0` and `z^2 \geq \mid ab \mid` to
  2528. a new reduced solution `(x', y', z')` such that `z'^2 \leq \mid ab \mid`.
  2529. The algorithm is an interpretation of Mordell's reduction as described
  2530. on page 8 of Cremona and Rusin's paper [1]_ and the work of Mordell in
  2531. reference [2]_.
  2532. References
  2533. ==========
  2534. .. [1] Cremona, J. E., Rusin, D. (2003). Efficient Solution of Rational Conics.
  2535. Mathematics of Computation, 72(243), 1417-1441.
  2536. https://doi.org/10.1090/S0025-5718-02-01480-1
  2537. .. [2] Diophantine Equations, L. J. Mordell, page 48.
  2538. """
  2539. if _odd(c):
  2540. k = 2*c
  2541. else:
  2542. k = c//2
  2543. small = a*b*c
  2544. step = 0
  2545. while True:
  2546. t1, t2, t3 = a*x**2, b*y**2, c*z**2
  2547. # check that it's a solution
  2548. if t1 + t2 != t3:
  2549. if step == 0:
  2550. raise ValueError('bad starting solution')
  2551. break
  2552. x_0, y_0, z_0 = x, y, z
  2553. if max(t1, t2, t3) <= small:
  2554. # Holzer condition
  2555. break
  2556. uv = u, v = base_solution_linear(k, y_0, -x_0)
  2557. if None in uv:
  2558. break
  2559. p, q = -(a*u*x_0 + b*v*y_0), c*z_0
  2560. r = Rational(p, q)
  2561. if _even(c):
  2562. w = _nint_or_floor(p, q)
  2563. assert abs(w - r) <= S.Half
  2564. else:
  2565. w = p//q # floor
  2566. if _odd(a*u + b*v + c*w):
  2567. w += 1
  2568. assert abs(w - r) <= S.One
  2569. A = (a*u**2 + b*v**2 + c*w**2)
  2570. B = (a*u*x_0 + b*v*y_0 + c*w*z_0)
  2571. x = Rational(x_0*A - 2*u*B, k)
  2572. y = Rational(y_0*A - 2*v*B, k)
  2573. z = Rational(z_0*A - 2*w*B, k)
  2574. assert all(i.is_Integer for i in (x, y, z))
  2575. step += 1
  2576. return tuple([int(i) for i in (x_0, y_0, z_0)])
  2577. def diop_general_pythagorean(eq, param=symbols("m", integer=True)):
  2578. """
  2579. Solves the general pythagorean equation,
  2580. `a_{1}^2x_{1}^2 + a_{2}^2x_{2}^2 + . . . + a_{n}^2x_{n}^2 - a_{n + 1}^2x_{n + 1}^2 = 0`.
  2581. Returns a tuple which contains a parametrized solution to the equation,
  2582. sorted in the same order as the input variables.
  2583. Usage
  2584. =====
  2585. ``diop_general_pythagorean(eq, param)``: where ``eq`` is a general
  2586. pythagorean equation which is assumed to be zero and ``param`` is the base
  2587. parameter used to construct other parameters by subscripting.
  2588. Examples
  2589. ========
  2590. >>> from sympy.solvers.diophantine.diophantine import diop_general_pythagorean
  2591. >>> from sympy.abc import a, b, c, d, e
  2592. >>> diop_general_pythagorean(a**2 + b**2 + c**2 - d**2)
  2593. (m1**2 + m2**2 - m3**2, 2*m1*m3, 2*m2*m3, m1**2 + m2**2 + m3**2)
  2594. >>> diop_general_pythagorean(9*a**2 - 4*b**2 + 16*c**2 + 25*d**2 + e**2)
  2595. (10*m1**2 + 10*m2**2 + 10*m3**2 - 10*m4**2, 15*m1**2 + 15*m2**2 + 15*m3**2 + 15*m4**2, 15*m1*m4, 12*m2*m4, 60*m3*m4)
  2596. """
  2597. var, coeff, diop_type = classify_diop(eq, _dict=False)
  2598. if diop_type == GeneralPythagorean.name:
  2599. if param is None:
  2600. params = None
  2601. else:
  2602. params = symbols('%s1:%i' % (param, len(var)), integer=True)
  2603. return list(GeneralPythagorean(eq).solve(parameters=params))[0]
  2604. def diop_general_sum_of_squares(eq, limit=1):
  2605. r"""
  2606. Solves the equation `x_{1}^2 + x_{2}^2 + . . . + x_{n}^2 - k = 0`.
  2607. Returns at most ``limit`` number of solutions.
  2608. Usage
  2609. =====
  2610. ``general_sum_of_squares(eq, limit)`` : Here ``eq`` is an expression which
  2611. is assumed to be zero. Also, ``eq`` should be in the form,
  2612. `x_{1}^2 + x_{2}^2 + . . . + x_{n}^2 - k = 0`.
  2613. Details
  2614. =======
  2615. When `n = 3` if `k = 4^a(8m + 7)` for some `a, m \in Z` then there will be
  2616. no solutions. Refer to [1]_ for more details.
  2617. Examples
  2618. ========
  2619. >>> from sympy.solvers.diophantine.diophantine import diop_general_sum_of_squares
  2620. >>> from sympy.abc import a, b, c, d, e
  2621. >>> diop_general_sum_of_squares(a**2 + b**2 + c**2 + d**2 + e**2 - 2345)
  2622. {(15, 22, 22, 24, 24)}
  2623. Reference
  2624. =========
  2625. .. [1] Representing an integer as a sum of three squares, [online],
  2626. Available:
  2627. https://proofwiki.org/wiki/Integer_as_Sum_of_Three_Squares
  2628. """
  2629. var, coeff, diop_type = classify_diop(eq, _dict=False)
  2630. if diop_type == GeneralSumOfSquares.name:
  2631. return set(GeneralSumOfSquares(eq).solve(limit=limit))
  2632. def diop_general_sum_of_even_powers(eq, limit=1):
  2633. """
  2634. Solves the equation `x_{1}^e + x_{2}^e + . . . + x_{n}^e - k = 0`
  2635. where `e` is an even, integer power.
  2636. Returns at most ``limit`` number of solutions.
  2637. Usage
  2638. =====
  2639. ``general_sum_of_even_powers(eq, limit)`` : Here ``eq`` is an expression which
  2640. is assumed to be zero. Also, ``eq`` should be in the form,
  2641. `x_{1}^e + x_{2}^e + . . . + x_{n}^e - k = 0`.
  2642. Examples
  2643. ========
  2644. >>> from sympy.solvers.diophantine.diophantine import diop_general_sum_of_even_powers
  2645. >>> from sympy.abc import a, b
  2646. >>> diop_general_sum_of_even_powers(a**4 + b**4 - (2**4 + 3**4))
  2647. {(2, 3)}
  2648. See Also
  2649. ========
  2650. power_representation
  2651. """
  2652. var, coeff, diop_type = classify_diop(eq, _dict=False)
  2653. if diop_type == GeneralSumOfEvenPowers.name:
  2654. return set(GeneralSumOfEvenPowers(eq).solve(limit=limit))
  2655. ## Functions below this comment can be more suitably grouped under
  2656. ## an Additive number theory module rather than the Diophantine
  2657. ## equation module.
  2658. def partition(n, k=None, zeros=False):
  2659. """
  2660. Returns a generator that can be used to generate partitions of an integer
  2661. `n`.
  2662. Explanation
  2663. ===========
  2664. A partition of `n` is a set of positive integers which add up to `n`. For
  2665. example, partitions of 3 are 3, 1 + 2, 1 + 1 + 1. A partition is returned
  2666. as a tuple. If ``k`` equals None, then all possible partitions are returned
  2667. irrespective of their size, otherwise only the partitions of size ``k`` are
  2668. returned. If the ``zero`` parameter is set to True then a suitable
  2669. number of zeros are added at the end of every partition of size less than
  2670. ``k``.
  2671. ``zero`` parameter is considered only if ``k`` is not None. When the
  2672. partitions are over, the last `next()` call throws the ``StopIteration``
  2673. exception, so this function should always be used inside a try - except
  2674. block.
  2675. Details
  2676. =======
  2677. ``partition(n, k)``: Here ``n`` is a positive integer and ``k`` is the size
  2678. of the partition which is also positive integer.
  2679. Examples
  2680. ========
  2681. >>> from sympy.solvers.diophantine.diophantine import partition
  2682. >>> f = partition(5)
  2683. >>> next(f)
  2684. (1, 1, 1, 1, 1)
  2685. >>> next(f)
  2686. (1, 1, 1, 2)
  2687. >>> g = partition(5, 3)
  2688. >>> next(g)
  2689. (1, 1, 3)
  2690. >>> next(g)
  2691. (1, 2, 2)
  2692. >>> g = partition(5, 3, zeros=True)
  2693. >>> next(g)
  2694. (0, 0, 5)
  2695. """
  2696. if not zeros or k is None:
  2697. for i in ordered_partitions(n, k):
  2698. yield tuple(i)
  2699. else:
  2700. for m in range(1, k + 1):
  2701. for i in ordered_partitions(n, m):
  2702. i = tuple(i)
  2703. yield (0,)*(k - len(i)) + i
  2704. def prime_as_sum_of_two_squares(p):
  2705. """
  2706. Represent a prime `p` as a unique sum of two squares; this can
  2707. only be done if the prime is congruent to 1 mod 4.
  2708. Parameters
  2709. ==========
  2710. p : Integer
  2711. A prime that is congruent to 1 mod 4
  2712. Returns
  2713. =======
  2714. (int, int) | None : Pair of positive integers ``(x, y)`` satisfying ``x**2 + y**2 = p``.
  2715. None if ``p`` is not congruent to 1 mod 4.
  2716. Raises
  2717. ======
  2718. ValueError
  2719. If ``p`` is not prime number
  2720. Examples
  2721. ========
  2722. >>> from sympy.solvers.diophantine.diophantine import prime_as_sum_of_two_squares
  2723. >>> prime_as_sum_of_two_squares(7) # can't be done
  2724. >>> prime_as_sum_of_two_squares(5)
  2725. (1, 2)
  2726. Reference
  2727. =========
  2728. .. [1] Representing a number as a sum of four squares, [online],
  2729. Available: https://schorn.ch/lagrange.html
  2730. See Also
  2731. ========
  2732. sum_of_squares
  2733. """
  2734. p = as_int(p)
  2735. if p % 4 != 1:
  2736. return
  2737. if not isprime(p):
  2738. raise ValueError("p should be a prime number")
  2739. if p % 8 == 5:
  2740. # Legendre symbol (2/p) == -1 if p % 8 in [3, 5]
  2741. b = 2
  2742. elif p % 12 == 5:
  2743. # Legendre symbol (3/p) == -1 if p % 12 in [5, 7]
  2744. b = 3
  2745. elif p % 5 in [2, 3]:
  2746. # Legendre symbol (5/p) == -1 if p % 5 in [2, 3]
  2747. b = 5
  2748. else:
  2749. b = 7
  2750. while jacobi(b, p) == 1:
  2751. b = nextprime(b)
  2752. b = pow(b, p >> 2, p)
  2753. a = p
  2754. while b**2 > p:
  2755. a, b = b, a % b
  2756. return (int(a % b), int(b)) # convert from long
  2757. def sum_of_three_squares(n):
  2758. r"""
  2759. Returns a 3-tuple $(a, b, c)$ such that $a^2 + b^2 + c^2 = n$ and
  2760. $a, b, c \geq 0$.
  2761. Returns None if $n = 4^a(8m + 7)$ for some `a, m \in \mathbb{Z}`. See
  2762. [1]_ for more details.
  2763. Parameters
  2764. ==========
  2765. n : Integer
  2766. non-negative integer
  2767. Returns
  2768. =======
  2769. (int, int, int) | None : 3-tuple non-negative integers ``(a, b, c)`` satisfying ``a**2 + b**2 + c**2 = n``.
  2770. a,b,c are sorted in ascending order. ``None`` if no such ``(a,b,c)``.
  2771. Raises
  2772. ======
  2773. ValueError
  2774. If ``n`` is a negative integer
  2775. Examples
  2776. ========
  2777. >>> from sympy.solvers.diophantine.diophantine import sum_of_three_squares
  2778. >>> sum_of_three_squares(44542)
  2779. (18, 37, 207)
  2780. References
  2781. ==========
  2782. .. [1] Representing a number as a sum of three squares, [online],
  2783. Available: https://schorn.ch/lagrange.html
  2784. See Also
  2785. ========
  2786. power_representation :
  2787. ``sum_of_three_squares(n)`` is one of the solutions output by ``power_representation(n, 2, 3, zeros=True)``
  2788. """
  2789. # https://math.stackexchange.com/questions/483101/rabin-and-shallit-algorithm/651425#651425
  2790. # discusses these numbers (except for 1, 2, 3) as the exceptions of H&L's conjecture that
  2791. # Every sufficiently large number n is either a square or the sum of a prime and a square.
  2792. special = {1: (0, 0, 1), 2: (0, 1, 1), 3: (1, 1, 1), 10: (0, 1, 3), 34: (3, 3, 4),
  2793. 58: (0, 3, 7), 85: (0, 6, 7), 130: (0, 3, 11), 214: (3, 6, 13), 226: (8, 9, 9),
  2794. 370: (8, 9, 15), 526: (6, 7, 21), 706: (15, 15, 16), 730: (0, 1, 27),
  2795. 1414: (6, 17, 33), 1906: (13, 21, 36), 2986: (21, 32, 39), 9634: (56, 57, 57)}
  2796. n = as_int(n)
  2797. if n < 0:
  2798. raise ValueError("n should be a non-negative integer")
  2799. if n == 0:
  2800. return (0, 0, 0)
  2801. n, v = remove(n, 4)
  2802. v = 1 << v
  2803. if n % 8 == 7:
  2804. return
  2805. if n in special:
  2806. return tuple([v*i for i in special[n]])
  2807. s, _exact = integer_nthroot(n, 2)
  2808. if _exact:
  2809. return (0, 0, v*s)
  2810. if n % 8 == 3:
  2811. if not s % 2:
  2812. s -= 1
  2813. for x in range(s, -1, -2):
  2814. N = (n - x**2) // 2
  2815. if isprime(N):
  2816. # n % 8 == 3 and x % 2 == 1 => N % 4 == 1
  2817. y, z = prime_as_sum_of_two_squares(N)
  2818. return tuple(sorted([v*x, v*(y + z), v*abs(y - z)]))
  2819. # We will never reach this point because there must be a solution.
  2820. assert False
  2821. # assert n % 4 in [1, 2]
  2822. if not((n % 2) ^ (s % 2)):
  2823. s -= 1
  2824. for x in range(s, -1, -2):
  2825. N = n - x**2
  2826. if isprime(N):
  2827. # assert N % 4 == 1
  2828. y, z = prime_as_sum_of_two_squares(N)
  2829. return tuple(sorted([v*x, v*y, v*z]))
  2830. # We will never reach this point because there must be a solution.
  2831. assert False
  2832. def sum_of_four_squares(n):
  2833. r"""
  2834. Returns a 4-tuple `(a, b, c, d)` such that `a^2 + b^2 + c^2 + d^2 = n`.
  2835. Here `a, b, c, d \geq 0`.
  2836. Parameters
  2837. ==========
  2838. n : Integer
  2839. non-negative integer
  2840. Returns
  2841. =======
  2842. (int, int, int, int) : 4-tuple non-negative integers ``(a, b, c, d)`` satisfying ``a**2 + b**2 + c**2 + d**2 = n``.
  2843. a,b,c,d are sorted in ascending order.
  2844. Raises
  2845. ======
  2846. ValueError
  2847. If ``n`` is a negative integer
  2848. Examples
  2849. ========
  2850. >>> from sympy.solvers.diophantine.diophantine import sum_of_four_squares
  2851. >>> sum_of_four_squares(3456)
  2852. (8, 8, 32, 48)
  2853. >>> sum_of_four_squares(1294585930293)
  2854. (0, 1234, 2161, 1137796)
  2855. References
  2856. ==========
  2857. .. [1] Representing a number as a sum of four squares, [online],
  2858. Available: https://schorn.ch/lagrange.html
  2859. See Also
  2860. ========
  2861. power_representation :
  2862. ``sum_of_four_squares(n)`` is one of the solutions output by ``power_representation(n, 2, 4, zeros=True)``
  2863. """
  2864. n = as_int(n)
  2865. if n < 0:
  2866. raise ValueError("n should be a non-negative integer")
  2867. if n == 0:
  2868. return (0, 0, 0, 0)
  2869. # remove factors of 4 since a solution in terms of 3 squares is
  2870. # going to be returned; this is also done in sum_of_three_squares,
  2871. # but it needs to be done here to select d
  2872. n, v = remove(n, 4)
  2873. v = 1 << v
  2874. if n % 8 == 7:
  2875. d = 2
  2876. n = n - 4
  2877. elif n % 8 in (2, 6):
  2878. d = 1
  2879. n = n - 1
  2880. else:
  2881. d = 0
  2882. x, y, z = sum_of_three_squares(n) # sorted
  2883. return tuple(sorted([v*d, v*x, v*y, v*z]))
  2884. def power_representation(n, p, k, zeros=False):
  2885. r"""
  2886. Returns a generator for finding k-tuples of integers,
  2887. `(n_{1}, n_{2}, . . . n_{k})`, such that
  2888. `n = n_{1}^p + n_{2}^p + . . . n_{k}^p`.
  2889. Usage
  2890. =====
  2891. ``power_representation(n, p, k, zeros)``: Represent non-negative number
  2892. ``n`` as a sum of ``k`` ``p``\ th powers. If ``zeros`` is true, then the
  2893. solutions is allowed to contain zeros.
  2894. Examples
  2895. ========
  2896. >>> from sympy.solvers.diophantine.diophantine import power_representation
  2897. Represent 1729 as a sum of two cubes:
  2898. >>> f = power_representation(1729, 3, 2)
  2899. >>> next(f)
  2900. (9, 10)
  2901. >>> next(f)
  2902. (1, 12)
  2903. If the flag `zeros` is True, the solution may contain tuples with
  2904. zeros; any such solutions will be generated after the solutions
  2905. without zeros:
  2906. >>> list(power_representation(125, 2, 3, zeros=True))
  2907. [(5, 6, 8), (3, 4, 10), (0, 5, 10), (0, 2, 11)]
  2908. For even `p` the `permute_sign` function can be used to get all
  2909. signed values:
  2910. >>> from sympy.utilities.iterables import permute_signs
  2911. >>> list(permute_signs((1, 12)))
  2912. [(1, 12), (-1, 12), (1, -12), (-1, -12)]
  2913. All possible signed permutations can also be obtained:
  2914. >>> from sympy.utilities.iterables import signed_permutations
  2915. >>> list(signed_permutations((1, 12)))
  2916. [(1, 12), (-1, 12), (1, -12), (-1, -12), (12, 1), (-12, 1), (12, -1), (-12, -1)]
  2917. """
  2918. n, p, k = [as_int(i) for i in (n, p, k)]
  2919. if n < 0:
  2920. if p % 2:
  2921. for t in power_representation(-n, p, k, zeros):
  2922. yield tuple(-i for i in t)
  2923. return
  2924. if p < 1 or k < 1:
  2925. raise ValueError(filldedent('''
  2926. Expecting positive integers for `(p, k)`, but got `(%s, %s)`'''
  2927. % (p, k)))
  2928. if n == 0:
  2929. if zeros:
  2930. yield (0,)*k
  2931. return
  2932. if k == 1:
  2933. if p == 1:
  2934. yield (n,)
  2935. elif n == 1:
  2936. yield (1,)
  2937. else:
  2938. be = perfect_power(n)
  2939. if be:
  2940. b, e = be
  2941. d, r = divmod(e, p)
  2942. if not r:
  2943. yield (b**d,)
  2944. return
  2945. if p == 1:
  2946. yield from partition(n, k, zeros=zeros)
  2947. return
  2948. if p == 2:
  2949. if k == 3:
  2950. n, v = remove(n, 4)
  2951. if v:
  2952. v = 1 << v
  2953. for t in power_representation(n, p, k, zeros):
  2954. yield tuple(i*v for i in t)
  2955. return
  2956. feasible = _can_do_sum_of_squares(n, k)
  2957. if not feasible:
  2958. return
  2959. if not zeros:
  2960. if n > 33 and k >= 5 and k <= n and n - k in (
  2961. 13, 10, 7, 5, 4, 2, 1):
  2962. '''Todd G. Will, "When Is n^2 a Sum of k Squares?", [online].
  2963. Available: https://www.maa.org/sites/default/files/Will-MMz-201037918.pdf'''
  2964. return
  2965. # quick tests since feasibility includes the possibility of 0
  2966. if k == 4 and (n in (1, 3, 5, 9, 11, 17, 29, 41) or remove(n, 4)[0] in (2, 6, 14)):
  2967. # A000534
  2968. return
  2969. if k == 3 and n in (1, 2, 5, 10, 13, 25, 37, 58, 85, 130): # or n = some number >= 5*10**10
  2970. # A051952
  2971. return
  2972. if feasible is not True: # it's prime and k == 2
  2973. yield prime_as_sum_of_two_squares(n)
  2974. return
  2975. if k == 2 and p > 2:
  2976. be = perfect_power(n)
  2977. if be and be[1] % p == 0:
  2978. return # Fermat: a**n + b**n = c**n has no solution for n > 2
  2979. if n >= k:
  2980. a = integer_nthroot(n - (k - 1), p)[0]
  2981. for t in pow_rep_recursive(a, k, n, [], p):
  2982. yield tuple(reversed(t))
  2983. if zeros:
  2984. a = integer_nthroot(n, p)[0]
  2985. for i in range(1, k):
  2986. for t in pow_rep_recursive(a, i, n, [], p):
  2987. yield tuple(reversed(t + (0,)*(k - i)))
  2988. sum_of_powers = power_representation
  2989. def pow_rep_recursive(n_i, k, n_remaining, terms, p):
  2990. # Invalid arguments
  2991. if n_i <= 0 or k <= 0:
  2992. return
  2993. # No solutions may exist
  2994. if n_remaining < k:
  2995. return
  2996. if k * pow(n_i, p) < n_remaining:
  2997. return
  2998. if k == 0 and n_remaining == 0:
  2999. yield tuple(terms)
  3000. elif k == 1:
  3001. # next_term^p must equal to n_remaining
  3002. next_term, exact = integer_nthroot(n_remaining, p)
  3003. if exact and next_term <= n_i:
  3004. yield tuple(terms + [next_term])
  3005. return
  3006. else:
  3007. # TODO: Fall back to diop_DN when k = 2
  3008. if n_i >= 1 and k > 0:
  3009. for next_term in range(1, n_i + 1):
  3010. residual = n_remaining - pow(next_term, p)
  3011. if residual < 0:
  3012. break
  3013. yield from pow_rep_recursive(next_term, k - 1, residual, terms + [next_term], p)
  3014. def sum_of_squares(n, k, zeros=False):
  3015. """Return a generator that yields the k-tuples of nonnegative
  3016. values, the squares of which sum to n. If zeros is False (default)
  3017. then the solution will not contain zeros. The nonnegative
  3018. elements of a tuple are sorted.
  3019. * If k == 1 and n is square, (n,) is returned.
  3020. * If k == 2 then n can only be written as a sum of squares if
  3021. every prime in the factorization of n that has the form
  3022. 4*k + 3 has an even multiplicity. If n is prime then
  3023. it can only be written as a sum of two squares if it is
  3024. in the form 4*k + 1.
  3025. * if k == 3 then n can be written as a sum of squares if it does
  3026. not have the form 4**m*(8*k + 7).
  3027. * all integers can be written as the sum of 4 squares.
  3028. * if k > 4 then n can be partitioned and each partition can
  3029. be written as a sum of 4 squares; if n is not evenly divisible
  3030. by 4 then n can be written as a sum of squares only if the
  3031. an additional partition can be written as sum of squares.
  3032. For example, if k = 6 then n is partitioned into two parts,
  3033. the first being written as a sum of 4 squares and the second
  3034. being written as a sum of 2 squares -- which can only be
  3035. done if the condition above for k = 2 can be met, so this will
  3036. automatically reject certain partitions of n.
  3037. Examples
  3038. ========
  3039. >>> from sympy.solvers.diophantine.diophantine import sum_of_squares
  3040. >>> list(sum_of_squares(25, 2))
  3041. [(3, 4)]
  3042. >>> list(sum_of_squares(25, 2, True))
  3043. [(3, 4), (0, 5)]
  3044. >>> list(sum_of_squares(25, 4))
  3045. [(1, 2, 2, 4)]
  3046. See Also
  3047. ========
  3048. sympy.utilities.iterables.signed_permutations
  3049. """
  3050. yield from power_representation(n, 2, k, zeros)
  3051. def _can_do_sum_of_squares(n, k):
  3052. """Return True if n can be written as the sum of k squares,
  3053. False if it cannot, or 1 if ``k == 2`` and ``n`` is prime (in which
  3054. case it *can* be written as a sum of two squares). A False
  3055. is returned only if it cannot be written as ``k``-squares, even
  3056. if 0s are allowed.
  3057. """
  3058. if k < 1:
  3059. return False
  3060. if n < 0:
  3061. return False
  3062. if n == 0:
  3063. return True
  3064. if k == 1:
  3065. return is_square(n)
  3066. if k == 2:
  3067. if n in (1, 2):
  3068. return True
  3069. if isprime(n):
  3070. if n % 4 == 1:
  3071. return 1 # signal that it was prime
  3072. return False
  3073. # n is a composite number
  3074. # we can proceed iff no prime factor in the form 4*k + 3
  3075. # has an odd multiplicity
  3076. return all(p % 4 !=3 or m % 2 == 0 for p, m in factorint(n).items())
  3077. if k == 3:
  3078. return remove(n, 4)[0] % 8 != 7
  3079. # every number can be written as a sum of 4 squares; for k > 4 partitions
  3080. # can be 0
  3081. return True