factor_.py 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841
  1. """
  2. Integer factorization
  3. """
  4. from __future__ import annotations
  5. from bisect import bisect_left
  6. from collections import defaultdict, OrderedDict
  7. from collections.abc import MutableMapping
  8. import math
  9. from sympy.core.containers import Dict
  10. from sympy.core.mul import Mul
  11. from sympy.core.numbers import Rational, Integer
  12. from sympy.core.intfunc import num_digits
  13. from sympy.core.power import Pow
  14. from sympy.core.random import _randint
  15. from sympy.core.singleton import S
  16. from sympy.external.gmpy import (SYMPY_INTS, gcd, sqrt as isqrt,
  17. sqrtrem, iroot, bit_scan1, remove)
  18. from .primetest import isprime, MERSENNE_PRIME_EXPONENTS, is_mersenne_prime
  19. from .generate import sieve, primerange, nextprime
  20. from .digits import digits
  21. from sympy.utilities.decorator import deprecated
  22. from sympy.utilities.iterables import flatten
  23. from sympy.utilities.misc import as_int, filldedent
  24. from .ecm import _ecm_one_factor
  25. def smoothness(n):
  26. """
  27. Return the B-smooth and B-power smooth values of n.
  28. The smoothness of n is the largest prime factor of n; the power-
  29. smoothness is the largest divisor raised to its multiplicity.
  30. Examples
  31. ========
  32. >>> from sympy.ntheory.factor_ import smoothness
  33. >>> smoothness(2**7*3**2)
  34. (3, 128)
  35. >>> smoothness(2**4*13)
  36. (13, 16)
  37. >>> smoothness(2)
  38. (2, 2)
  39. See Also
  40. ========
  41. factorint, smoothness_p
  42. """
  43. if n == 1:
  44. return (1, 1) # not prime, but otherwise this causes headaches
  45. facs = factorint(n)
  46. return max(facs), max(m**facs[m] for m in facs)
  47. def smoothness_p(n, m=-1, power=0, visual=None):
  48. """
  49. Return a list of [m, (p, (M, sm(p + m), psm(p + m)))...]
  50. where:
  51. 1. p**M is the base-p divisor of n
  52. 2. sm(p + m) is the smoothness of p + m (m = -1 by default)
  53. 3. psm(p + m) is the power smoothness of p + m
  54. The list is sorted according to smoothness (default) or by power smoothness
  55. if power=1.
  56. The smoothness of the numbers to the left (m = -1) or right (m = 1) of a
  57. factor govern the results that are obtained from the p +/- 1 type factoring
  58. methods.
  59. >>> from sympy.ntheory.factor_ import smoothness_p, factorint
  60. >>> smoothness_p(10431, m=1)
  61. (1, [(3, (2, 2, 4)), (19, (1, 5, 5)), (61, (1, 31, 31))])
  62. >>> smoothness_p(10431)
  63. (-1, [(3, (2, 2, 2)), (19, (1, 3, 9)), (61, (1, 5, 5))])
  64. >>> smoothness_p(10431, power=1)
  65. (-1, [(3, (2, 2, 2)), (61, (1, 5, 5)), (19, (1, 3, 9))])
  66. If visual=True then an annotated string will be returned:
  67. >>> print(smoothness_p(21477639576571, visual=1))
  68. p**i=4410317**1 has p-1 B=1787, B-pow=1787
  69. p**i=4869863**1 has p-1 B=2434931, B-pow=2434931
  70. This string can also be generated directly from a factorization dictionary
  71. and vice versa:
  72. >>> factorint(17*9)
  73. {3: 2, 17: 1}
  74. >>> smoothness_p(_)
  75. 'p**i=3**2 has p-1 B=2, B-pow=2\\np**i=17**1 has p-1 B=2, B-pow=16'
  76. >>> smoothness_p(_)
  77. {3: 2, 17: 1}
  78. The table of the output logic is:
  79. ====== ====== ======= =======
  80. | Visual
  81. ------ ----------------------
  82. Input True False other
  83. ====== ====== ======= =======
  84. dict str tuple str
  85. str str tuple dict
  86. tuple str tuple str
  87. n str tuple tuple
  88. mul str tuple tuple
  89. ====== ====== ======= =======
  90. See Also
  91. ========
  92. factorint, smoothness
  93. """
  94. # visual must be True, False or other (stored as None)
  95. if visual in (1, 0):
  96. visual = bool(visual)
  97. elif visual not in (True, False):
  98. visual = None
  99. if isinstance(n, str):
  100. if visual:
  101. return n
  102. d = {}
  103. for li in n.splitlines():
  104. k, v = [int(i) for i in
  105. li.split('has')[0].split('=')[1].split('**')]
  106. d[k] = v
  107. if visual is not True and visual is not False:
  108. return d
  109. return smoothness_p(d, visual=False)
  110. elif not isinstance(n, tuple):
  111. facs = factorint(n, visual=False)
  112. if power:
  113. k = -1
  114. else:
  115. k = 1
  116. if isinstance(n, tuple):
  117. rv = n
  118. else:
  119. rv = (m, sorted([(f,
  120. tuple([M] + list(smoothness(f + m))))
  121. for f, M in list(facs.items())],
  122. key=lambda x: (x[1][k], x[0])))
  123. if visual is False or (visual is not True) and (type(n) in [int, Mul]):
  124. return rv
  125. lines = []
  126. for dat in rv[1]:
  127. dat = flatten(dat)
  128. dat.insert(2, m)
  129. lines.append('p**i=%i**%i has p%+i B=%i, B-pow=%i' % tuple(dat))
  130. return '\n'.join(lines)
  131. def multiplicity(p, n):
  132. """
  133. Find the greatest integer m such that p**m divides n.
  134. Examples
  135. ========
  136. >>> from sympy import multiplicity, Rational
  137. >>> [multiplicity(5, n) for n in [8, 5, 25, 125, 250]]
  138. [0, 1, 2, 3, 3]
  139. >>> multiplicity(3, Rational(1, 9))
  140. -2
  141. Note: when checking for the multiplicity of a number in a
  142. large factorial it is most efficient to send it as an unevaluated
  143. factorial or to call ``multiplicity_in_factorial`` directly:
  144. >>> from sympy.ntheory import multiplicity_in_factorial
  145. >>> from sympy import factorial
  146. >>> p = factorial(25)
  147. >>> n = 2**100
  148. >>> nfac = factorial(n, evaluate=False)
  149. >>> multiplicity(p, nfac)
  150. 52818775009509558395695966887
  151. >>> _ == multiplicity_in_factorial(p, n)
  152. True
  153. See Also
  154. ========
  155. trailing
  156. """
  157. try:
  158. p, n = as_int(p), as_int(n)
  159. except ValueError:
  160. from sympy.functions.combinatorial.factorials import factorial
  161. if all(isinstance(i, (SYMPY_INTS, Rational)) for i in (p, n)):
  162. p = Rational(p)
  163. n = Rational(n)
  164. if p.q == 1:
  165. if n.p == 1:
  166. return -multiplicity(p.p, n.q)
  167. return multiplicity(p.p, n.p) - multiplicity(p.p, n.q)
  168. elif p.p == 1:
  169. return multiplicity(p.q, n.q)
  170. else:
  171. like = min(
  172. multiplicity(p.p, n.p),
  173. multiplicity(p.q, n.q))
  174. cross = min(
  175. multiplicity(p.q, n.p),
  176. multiplicity(p.p, n.q))
  177. return like - cross
  178. elif (isinstance(p, (SYMPY_INTS, Integer)) and
  179. isinstance(n, factorial) and
  180. isinstance(n.args[0], Integer) and
  181. n.args[0] >= 0):
  182. return multiplicity_in_factorial(p, n.args[0])
  183. raise ValueError('expecting ints or fractions, got %s and %s' % (p, n))
  184. if n == 0:
  185. raise ValueError('no such integer exists: multiplicity of %s is not-defined' %(n))
  186. return remove(n, p)[1]
  187. def multiplicity_in_factorial(p, n):
  188. """return the largest integer ``m`` such that ``p**m`` divides ``n!``
  189. without calculating the factorial of ``n``.
  190. Parameters
  191. ==========
  192. p : Integer
  193. positive integer
  194. n : Integer
  195. non-negative integer
  196. Examples
  197. ========
  198. >>> from sympy.ntheory import multiplicity_in_factorial
  199. >>> from sympy import factorial
  200. >>> multiplicity_in_factorial(2, 3)
  201. 1
  202. An instructive use of this is to tell how many trailing zeros
  203. a given factorial has. For example, there are 6 in 25!:
  204. >>> factorial(25)
  205. 15511210043330985984000000
  206. >>> multiplicity_in_factorial(10, 25)
  207. 6
  208. For large factorials, it is much faster/feasible to use
  209. this function rather than computing the actual factorial:
  210. >>> multiplicity_in_factorial(factorial(25), 2**100)
  211. 52818775009509558395695966887
  212. See Also
  213. ========
  214. multiplicity
  215. """
  216. p, n = as_int(p), as_int(n)
  217. if p <= 0:
  218. raise ValueError('expecting positive integer got %s' % p )
  219. if n < 0:
  220. raise ValueError('expecting non-negative integer got %s' % n )
  221. # keep only the largest of a given multiplicity since those
  222. # of a given multiplicity will be goverened by the behavior
  223. # of the largest factor
  224. f = defaultdict(int)
  225. for k, v in factorint(p).items():
  226. f[v] = max(k, f[v])
  227. # multiplicity of p in n! depends on multiplicity
  228. # of prime `k` in p, so we floor divide by `v`
  229. # and keep it if smaller than the multiplicity of p
  230. # seen so far
  231. return min((n + k - sum(digits(n, k)))//(k - 1)//v for v, k in f.items())
  232. def _perfect_power(n, next_p=2):
  233. """ Return integers ``(b, e)`` such that ``n == b**e`` if ``n`` is a unique
  234. perfect power with ``e > 1``, else ``False`` (e.g. 1 is not a perfect power).
  235. Explanation
  236. ===========
  237. This is a low-level helper for ``perfect_power``, for internal use.
  238. Parameters
  239. ==========
  240. n : int
  241. assume that n is a nonnegative integer
  242. next_p : int
  243. Assume that n has no factor less than next_p.
  244. i.e., all(n % p for p in range(2, next_p)) is True
  245. Examples
  246. ========
  247. >>> from sympy.ntheory.factor_ import _perfect_power
  248. >>> _perfect_power(16)
  249. (2, 4)
  250. >>> _perfect_power(17)
  251. False
  252. """
  253. if n <= 3:
  254. return False
  255. factors = {}
  256. g = 0
  257. multi = 1
  258. def done(n, factors, g, multi):
  259. g = gcd(g, multi)
  260. if g == 1:
  261. return False
  262. factors[n] = multi
  263. return math.prod(p**(e//g) for p, e in factors.items()), g
  264. # If n is small, only trial factoring is faster
  265. if n <= 1_000_000:
  266. n = _factorint_small(factors, n, 1_000, 1_000, next_p)[0]
  267. if n > 1:
  268. return False
  269. g = gcd(*factors.values())
  270. if g == 1:
  271. return False
  272. return math.prod(p**(e//g) for p, e in factors.items()), g
  273. # divide by 2
  274. if next_p < 3:
  275. g = bit_scan1(n)
  276. if g:
  277. if g == 1:
  278. return False
  279. n >>= g
  280. factors[2] = g
  281. if n == 1:
  282. return 2, g
  283. else:
  284. # If `m**g`, then we have found perfect power.
  285. # Otherwise, there is no possibility of perfect power, especially if `g` is prime.
  286. m, _exact = iroot(n, g)
  287. if _exact:
  288. return 2*m, g
  289. elif isprime(g):
  290. return False
  291. next_p = 3
  292. # square number?
  293. while n & 7 == 1: # n % 8 == 1:
  294. m, _exact = iroot(n, 2)
  295. if _exact:
  296. n = m
  297. multi <<= 1
  298. else:
  299. break
  300. if n < next_p**3:
  301. return done(n, factors, g, multi)
  302. # trial factoring
  303. # Since the maximum value an exponent can take is `log_{next_p}(n)`,
  304. # the number of exponents to be checked can be reduced by performing a trial factoring.
  305. # The value of `tf_max` needs more consideration.
  306. tf_max = n.bit_length()//27 + 24
  307. if next_p < tf_max:
  308. for p in primerange(next_p, tf_max):
  309. m, t = remove(n, p)
  310. if t:
  311. n = m
  312. t *= multi
  313. _g = gcd(g, t)
  314. if _g == 1:
  315. return False
  316. factors[p] = t
  317. if n == 1:
  318. return math.prod(p**(e//_g)
  319. for p, e in factors.items()), _g
  320. elif g == 0 or _g < g: # If g is updated
  321. g = _g
  322. m, _exact = iroot(n**multi, g)
  323. if _exact:
  324. return m * math.prod(p**(e//g)
  325. for p, e in factors.items()), g
  326. elif isprime(g):
  327. return False
  328. next_p = tf_max
  329. if n < next_p**3:
  330. return done(n, factors, g, multi)
  331. # check iroot
  332. if g:
  333. # If g is non-zero, the exponent is a divisor of g.
  334. # 2 can be omitted since it has already been checked.
  335. prime_iter = sorted(factorint(g >> bit_scan1(g)).keys())
  336. else:
  337. # The maximum possible value of the exponent is `log_{next_p}(n)`.
  338. # To compensate for the presence of computational error, 2 is added.
  339. prime_iter = primerange(3, int(math.log(n, next_p)) + 2)
  340. logn = math.log2(n)
  341. threshold = logn / 40 # Threshold for direct calculation
  342. for p in prime_iter:
  343. if threshold < p:
  344. # If p is large, find the power root p directly without `iroot`.
  345. while True:
  346. b = pow(2, logn / p)
  347. rb = int(b + 0.5)
  348. if abs(rb - b) < 0.01 and rb**p == n:
  349. n = rb
  350. multi *= p
  351. logn = math.log2(n)
  352. else:
  353. break
  354. else:
  355. while True:
  356. m, _exact = iroot(n, p)
  357. if _exact:
  358. n = m
  359. multi *= p
  360. logn = math.log2(n)
  361. else:
  362. break
  363. if n < next_p**(p + 2):
  364. break
  365. return done(n, factors, g, multi)
  366. def perfect_power(n, candidates=None, big=True, factor=True):
  367. """
  368. Return ``(b, e)`` such that ``n`` == ``b**e`` if ``n`` is a unique
  369. perfect power with ``e > 1``, else ``False`` (e.g. 1 is not a
  370. perfect power). A ValueError is raised if ``n`` is not Rational.
  371. By default, the base is recursively decomposed and the exponents
  372. collected so the largest possible ``e`` is sought. If ``big=False``
  373. then the smallest possible ``e`` (thus prime) will be chosen.
  374. If ``factor=True`` then simultaneous factorization of ``n`` is
  375. attempted since finding a factor indicates the only possible root
  376. for ``n``. This is True by default since only a few small factors will
  377. be tested in the course of searching for the perfect power.
  378. The use of ``candidates`` is primarily for internal use; if provided,
  379. False will be returned if ``n`` cannot be written as a power with one
  380. of the candidates as an exponent and factoring (beyond testing for
  381. a factor of 2) will not be attempted.
  382. Examples
  383. ========
  384. >>> from sympy import perfect_power, Rational
  385. >>> perfect_power(16)
  386. (2, 4)
  387. >>> perfect_power(16, big=False)
  388. (4, 2)
  389. Negative numbers can only have odd perfect powers:
  390. >>> perfect_power(-4)
  391. False
  392. >>> perfect_power(-8)
  393. (-2, 3)
  394. Rationals are also recognized:
  395. >>> perfect_power(Rational(1, 2)**3)
  396. (1/2, 3)
  397. >>> perfect_power(Rational(-3, 2)**3)
  398. (-3/2, 3)
  399. Notes
  400. =====
  401. To know whether an integer is a perfect power of 2 use
  402. >>> is2pow = lambda n: bool(n and not n & (n - 1))
  403. >>> [(i, is2pow(i)) for i in range(5)]
  404. [(0, False), (1, True), (2, True), (3, False), (4, True)]
  405. It is not necessary to provide ``candidates``. When provided
  406. it will be assumed that they are ints. The first one that is
  407. larger than the computed maximum possible exponent will signal
  408. failure for the routine.
  409. >>> perfect_power(3**8, [9])
  410. False
  411. >>> perfect_power(3**8, [2, 4, 8])
  412. (3, 8)
  413. >>> perfect_power(3**8, [4, 8], big=False)
  414. (9, 4)
  415. See Also
  416. ========
  417. sympy.core.intfunc.integer_nthroot
  418. sympy.ntheory.primetest.is_square
  419. """
  420. # negative handling
  421. if n < 0:
  422. if candidates is None:
  423. pp = perfect_power(-n, big=True, factor=factor)
  424. if not pp:
  425. return False
  426. b, e = pp
  427. e2 = e & (-e)
  428. b, e = b ** e2, e // e2
  429. if e <= 1:
  430. return False
  431. if big or isprime(e):
  432. return -b, e
  433. for p in primerange(3, e + 1):
  434. if e % p == 0:
  435. return - b ** (e // p), p
  436. odd_candidates = {i for i in candidates if i % 2}
  437. if not odd_candidates:
  438. return False
  439. pp = perfect_power(-n, odd_candidates, big, factor)
  440. if pp:
  441. return -pp[0], pp[1]
  442. return False
  443. # non-integer handling
  444. if isinstance(n, Rational) and not isinstance(n, Integer):
  445. p, q = n.p, n.q
  446. if p == 1:
  447. qq = perfect_power(q, candidates, big, factor)
  448. return (S.One / qq[0], qq[1]) if qq is not False else False
  449. if not (pp:=perfect_power(p, factor=factor)):
  450. return False
  451. if not (qq:=perfect_power(q, factor=factor)):
  452. return False
  453. (num_base, num_exp), (den_base, den_exp) = pp, qq
  454. def compute_tuple(exponent):
  455. """Helper to compute final result given an exponent"""
  456. new_num = num_base ** (num_exp // exponent)
  457. new_den = den_base ** (den_exp // exponent)
  458. return n.func(new_num, new_den), exponent
  459. if candidates:
  460. valid_candidates = [i for i in candidates
  461. if num_exp % i == 0 and den_exp % i == 0]
  462. if not valid_candidates:
  463. return False
  464. e = max(valid_candidates) if big else min(valid_candidates)
  465. return compute_tuple(e)
  466. g = math.gcd(num_exp, den_exp)
  467. if g == 1:
  468. return False
  469. if big:
  470. return compute_tuple(g)
  471. e = next(p for p in primerange(2, g + 1) if g % p == 0)
  472. return compute_tuple(e)
  473. if candidates is not None:
  474. candidates = set(candidates)
  475. # positive integer handling
  476. n = as_int(n)
  477. if candidates is None and big:
  478. return _perfect_power(n)
  479. if n <= 3:
  480. # no unique exponent for 0, 1
  481. # 2 and 3 have exponents of 1
  482. return False
  483. logn = math.log2(n)
  484. max_possible = int(logn) + 2 # only check values less than this
  485. not_square = n % 10 in [2, 3, 7, 8] # squares cannot end in 2, 3, 7, 8
  486. min_possible = 2 + not_square
  487. if not candidates:
  488. candidates = primerange(min_possible, max_possible)
  489. else:
  490. candidates = sorted([i for i in candidates
  491. if min_possible <= i < max_possible])
  492. if n%2 == 0:
  493. e = bit_scan1(n)
  494. candidates = [i for i in candidates if e%i == 0]
  495. if big:
  496. candidates = reversed(candidates)
  497. for e in candidates:
  498. r, ok = iroot(n, e)
  499. if ok:
  500. return int(r), e
  501. return False
  502. def _factors():
  503. rv = 2 + n % 2
  504. while True:
  505. yield rv
  506. rv = nextprime(rv)
  507. for fac, e in zip(_factors(), candidates):
  508. # see if there is a factor present
  509. if factor and n % fac == 0:
  510. # find what the potential power is
  511. e = remove(n, fac)[1]
  512. # if it's a trivial power we are done
  513. if e == 1:
  514. return False
  515. # maybe the e-th root of n is exact
  516. r, exact = iroot(n, e)
  517. if not exact:
  518. # Having a factor, we know that e is the maximal
  519. # possible value for a root of n.
  520. # If n = fac**e*m can be written as a perfect
  521. # power then see if m can be written as r**E where
  522. # gcd(e, E) != 1 so n = (fac**(e//E)*r)**E
  523. m = n//fac**e
  524. rE = perfect_power(m, candidates=divisors(e, generator=True))
  525. if not rE:
  526. return False
  527. else:
  528. r, E = rE
  529. r, e = fac**(e//E)*r, E
  530. if not big:
  531. e0 = primefactors(e)
  532. if e0[0] != e:
  533. r, e = r**(e//e0[0]), e0[0]
  534. return int(r), e
  535. # Weed out downright impossible candidates
  536. if logn/e < 40:
  537. b = 2.0**(logn/e)
  538. if abs(int(b + 0.5) - b) > 0.01:
  539. continue
  540. # now see if the plausible e makes a perfect power
  541. r, exact = iroot(n, e)
  542. if exact:
  543. if big:
  544. m = perfect_power(r, big=big, factor=factor)
  545. if m:
  546. r, e = m[0], e*m[1]
  547. return int(r), e
  548. return False
  549. class FactorCache(MutableMapping):
  550. """ Provides a cache for prime factors.
  551. ``factor_cache`` is pre-prepared as an instance of ``FactorCache``,
  552. and ``factorint`` internally references it to speed up
  553. the factorization of prime factors.
  554. While cache is automatically added during the execution of ``factorint``,
  555. users can also manually add prime factors independently.
  556. >>> from sympy import factor_cache
  557. >>> factor_cache[15] = 5
  558. Furthermore, by customizing ``get_external``,
  559. it is also possible to use external databases.
  560. The following is an example using http://factordb.com .
  561. .. code-block:: python
  562. import requests
  563. from sympy import factor_cache
  564. def get_external(self, n: int) -> list[int] | None:
  565. res = requests.get("http://factordb.com/api", params={"query": str(n)})
  566. if res.status_code != requests.codes.ok:
  567. return None
  568. j = res.json()
  569. if j.get("status") in ["FF", "P"]:
  570. return list(int(p) for p, _ in j.get("factors"))
  571. factor_cache.get_external = get_external
  572. Be aware that writing this code will trigger internet access
  573. to factordb.com when calling ``factorint``.
  574. """
  575. def __init__(self, maxsize: int | None = None):
  576. self._cache: OrderedDict[int, int] = OrderedDict()
  577. self.maxsize = maxsize
  578. def __len__(self) -> int:
  579. return len(self._cache)
  580. def __contains__(self, n) -> bool:
  581. return n in self._cache
  582. def __getitem__(self, n: int) -> int:
  583. factor = self.get(n)
  584. if factor is None:
  585. raise KeyError(f"{n} does not exist.")
  586. return factor
  587. def __setitem__(self, n: int, factor: int):
  588. if not (1 < factor <= n and n % factor == 0 and isprime(factor)):
  589. raise ValueError(f"{factor} is not a prime factor of {n}")
  590. self._cache[n] = max(self._cache.get(n, 0), factor)
  591. if self.maxsize is not None and len(self._cache) > self.maxsize:
  592. self._cache.popitem(False)
  593. def __delitem__(self, n: int):
  594. if n not in self._cache:
  595. raise KeyError(f"{n} does not exist.")
  596. del self._cache[n]
  597. def __iter__(self):
  598. return self._cache.__iter__()
  599. def cache_clear(self) -> None:
  600. """ Clear the cache """
  601. self._cache = OrderedDict()
  602. @property
  603. def maxsize(self) -> int | None:
  604. """ Returns the maximum cache size; if ``None``, it is unlimited. """
  605. return self._maxsize
  606. @maxsize.setter
  607. def maxsize(self, value: int | None) -> None:
  608. if value is not None and value <= 0:
  609. raise ValueError("maxsize must be None or a non-negative integer.")
  610. self._maxsize = value
  611. if value is not None:
  612. while len(self._cache) > value:
  613. self._cache.popitem(False)
  614. def get(self, n: int, default=None):
  615. """ Return the prime factor of ``n``.
  616. If it does not exist in the cache, return the value of ``default``.
  617. """
  618. if n <= sieve._list[-1]:
  619. if sieve._list[bisect_left(sieve._list, n)] == n:
  620. return n
  621. if n in self._cache:
  622. self._cache.move_to_end(n)
  623. return self._cache[n]
  624. if factors := self.get_external(n):
  625. self.add(n, factors)
  626. return self._cache[n]
  627. return default
  628. def add(self, n: int, factors: list[int]) -> None:
  629. for p in sorted(factors, reverse=True):
  630. self[n] = p
  631. n, _ = remove(n, p)
  632. def get_external(self, n: int) -> list[int] | None:
  633. return None
  634. factor_cache = FactorCache(maxsize=1000)
  635. def pollard_rho(n, s=2, a=1, retries=5, seed=1234, max_steps=None, F=None):
  636. r"""
  637. Use Pollard's rho method to try to extract a nontrivial factor
  638. of ``n``. The returned factor may be a composite number. If no
  639. factor is found, ``None`` is returned.
  640. The algorithm generates pseudo-random values of x with a generator
  641. function, replacing x with F(x). If F is not supplied then the
  642. function x**2 + ``a`` is used. The first value supplied to F(x) is ``s``.
  643. Upon failure (if ``retries`` is > 0) a new ``a`` and ``s`` will be
  644. supplied; the ``a`` will be ignored if F was supplied.
  645. The sequence of numbers generated by such functions generally have a
  646. a lead-up to some number and then loop around back to that number and
  647. begin to repeat the sequence, e.g. 1, 2, 3, 4, 5, 3, 4, 5 -- this leader
  648. and loop look a bit like the Greek letter rho, and thus the name, 'rho'.
  649. For a given function, very different leader-loop values can be obtained
  650. so it is a good idea to allow for retries:
  651. >>> from sympy.ntheory.generate import cycle_length
  652. >>> n = 16843009
  653. >>> F = lambda x:(2048*pow(x, 2, n) + 32767) % n
  654. >>> for s in range(5):
  655. ... print('loop length = %4i; leader length = %3i' % next(cycle_length(F, s)))
  656. ...
  657. loop length = 2489; leader length = 43
  658. loop length = 78; leader length = 121
  659. loop length = 1482; leader length = 100
  660. loop length = 1482; leader length = 286
  661. loop length = 1482; leader length = 101
  662. Here is an explicit example where there is a three element leadup to
  663. a sequence of 3 numbers (11, 14, 4) that then repeat:
  664. >>> x=2
  665. >>> for i in range(9):
  666. ... print(x)
  667. ... x=(x**2+12)%17
  668. ...
  669. 2
  670. 16
  671. 13
  672. 11
  673. 14
  674. 4
  675. 11
  676. 14
  677. 4
  678. >>> next(cycle_length(lambda x: (x**2+12)%17, 2))
  679. (3, 3)
  680. >>> list(cycle_length(lambda x: (x**2+12)%17, 2, values=True))
  681. [2, 16, 13, 11, 14, 4]
  682. Instead of checking the differences of all generated values for a gcd
  683. with n, only the kth and 2*kth numbers are checked, e.g. 1st and 2nd,
  684. 2nd and 4th, 3rd and 6th until it has been detected that the loop has been
  685. traversed. Loops may be many thousands of steps long before rho finds a
  686. factor or reports failure. If ``max_steps`` is specified, the iteration
  687. is cancelled with a failure after the specified number of steps.
  688. Examples
  689. ========
  690. >>> from sympy import pollard_rho
  691. >>> n=16843009
  692. >>> F=lambda x:(2048*pow(x,2,n) + 32767) % n
  693. >>> pollard_rho(n, F=F)
  694. 257
  695. Use the default setting with a bad value of ``a`` and no retries:
  696. >>> pollard_rho(n, a=n-2, retries=0)
  697. If retries is > 0 then perhaps the problem will correct itself when
  698. new values are generated for a:
  699. >>> pollard_rho(n, a=n-2, retries=1)
  700. 257
  701. References
  702. ==========
  703. .. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers:
  704. A Computational Perspective", Springer, 2nd edition, 229-231
  705. """
  706. n = int(n)
  707. if n < 5:
  708. raise ValueError('pollard_rho should receive n > 4')
  709. randint = _randint(seed + retries)
  710. V = s
  711. for i in range(retries + 1):
  712. U = V
  713. if not F:
  714. F = lambda x: (pow(x, 2, n) + a) % n
  715. j = 0
  716. while 1:
  717. if max_steps and (j > max_steps):
  718. break
  719. j += 1
  720. U = F(U)
  721. V = F(F(V)) # V is 2x further along than U
  722. g = gcd(U - V, n)
  723. if g == 1:
  724. continue
  725. if g == n:
  726. break
  727. return int(g)
  728. V = randint(0, n - 1)
  729. a = randint(1, n - 3) # for x**2 + a, a%n should not be 0 or -2
  730. F = None
  731. return None
  732. def pollard_pm1(n, B=10, a=2, retries=0, seed=1234):
  733. """
  734. Use Pollard's p-1 method to try to extract a nontrivial factor
  735. of ``n``. Either a divisor (perhaps composite) or ``None`` is returned.
  736. The value of ``a`` is the base that is used in the test gcd(a**M - 1, n).
  737. The default is 2. If ``retries`` > 0 then if no factor is found after the
  738. first attempt, a new ``a`` will be generated randomly (using the ``seed``)
  739. and the process repeated.
  740. Note: the value of M is lcm(1..B) = reduce(ilcm, range(2, B + 1)).
  741. A search is made for factors next to even numbers having a power smoothness
  742. less than ``B``. Choosing a larger B increases the likelihood of finding a
  743. larger factor but takes longer. Whether a factor of n is found or not
  744. depends on ``a`` and the power smoothness of the even number just less than
  745. the factor p (hence the name p - 1).
  746. Although some discussion of what constitutes a good ``a`` some
  747. descriptions are hard to interpret. At the modular.math site referenced
  748. below it is stated that if gcd(a**M - 1, n) = N then a**M % q**r is 1
  749. for every prime power divisor of N. But consider the following:
  750. >>> from sympy.ntheory.factor_ import smoothness_p, pollard_pm1
  751. >>> n=257*1009
  752. >>> smoothness_p(n)
  753. (-1, [(257, (1, 2, 256)), (1009, (1, 7, 16))])
  754. So we should (and can) find a root with B=16:
  755. >>> pollard_pm1(n, B=16, a=3)
  756. 1009
  757. If we attempt to increase B to 256 we find that it does not work:
  758. >>> pollard_pm1(n, B=256)
  759. >>>
  760. But if the value of ``a`` is changed we find that only multiples of
  761. 257 work, e.g.:
  762. >>> pollard_pm1(n, B=256, a=257)
  763. 1009
  764. Checking different ``a`` values shows that all the ones that did not
  765. work had a gcd value not equal to ``n`` but equal to one of the
  766. factors:
  767. >>> from sympy import ilcm, igcd, factorint, Pow
  768. >>> M = 1
  769. >>> for i in range(2, 256):
  770. ... M = ilcm(M, i)
  771. ...
  772. >>> set([igcd(pow(a, M, n) - 1, n) for a in range(2, 256) if
  773. ... igcd(pow(a, M, n) - 1, n) != n])
  774. {1009}
  775. But does aM % d for every divisor of n give 1?
  776. >>> aM = pow(255, M, n)
  777. >>> [(d, aM%Pow(*d.args)) for d in factorint(n, visual=True).args]
  778. [(257**1, 1), (1009**1, 1)]
  779. No, only one of them. So perhaps the principle is that a root will
  780. be found for a given value of B provided that:
  781. 1) the power smoothness of the p - 1 value next to the root
  782. does not exceed B
  783. 2) a**M % p != 1 for any of the divisors of n.
  784. By trying more than one ``a`` it is possible that one of them
  785. will yield a factor.
  786. Examples
  787. ========
  788. With the default smoothness bound, this number cannot be cracked:
  789. >>> from sympy.ntheory import pollard_pm1
  790. >>> pollard_pm1(21477639576571)
  791. Increasing the smoothness bound helps:
  792. >>> pollard_pm1(21477639576571, B=2000)
  793. 4410317
  794. Looking at the smoothness of the factors of this number we find:
  795. >>> from sympy.ntheory.factor_ import smoothness_p, factorint
  796. >>> print(smoothness_p(21477639576571, visual=1))
  797. p**i=4410317**1 has p-1 B=1787, B-pow=1787
  798. p**i=4869863**1 has p-1 B=2434931, B-pow=2434931
  799. The B and B-pow are the same for the p - 1 factorizations of the divisors
  800. because those factorizations had a very large prime factor:
  801. >>> factorint(4410317 - 1)
  802. {2: 2, 617: 1, 1787: 1}
  803. >>> factorint(4869863-1)
  804. {2: 1, 2434931: 1}
  805. Note that until B reaches the B-pow value of 1787, the number is not cracked;
  806. >>> pollard_pm1(21477639576571, B=1786)
  807. >>> pollard_pm1(21477639576571, B=1787)
  808. 4410317
  809. The B value has to do with the factors of the number next to the divisor,
  810. not the divisors themselves. A worst case scenario is that the number next
  811. to the factor p has a large prime divisisor or is a perfect power. If these
  812. conditions apply then the power-smoothness will be about p/2 or p. The more
  813. realistic is that there will be a large prime factor next to p requiring
  814. a B value on the order of p/2. Although primes may have been searched for
  815. up to this level, the p/2 is a factor of p - 1, something that we do not
  816. know. The modular.math reference below states that 15% of numbers in the
  817. range of 10**15 to 15**15 + 10**4 are 10**6 power smooth so a B of 10**6
  818. will fail 85% of the time in that range. From 10**8 to 10**8 + 10**3 the
  819. percentages are nearly reversed...but in that range the simple trial
  820. division is quite fast.
  821. References
  822. ==========
  823. .. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers:
  824. A Computational Perspective", Springer, 2nd edition, 236-238
  825. .. [2] https://web.archive.org/web/20150716201437/http://modular.math.washington.edu/edu/2007/spring/ent/ent-html/node81.html
  826. .. [3] https://www.cs.toronto.edu/~yuvalf/Factorization.pdf
  827. """
  828. n = int(n)
  829. if n < 4 or B < 3:
  830. raise ValueError('pollard_pm1 should receive n > 3 and B > 2')
  831. randint = _randint(seed + B)
  832. # computing a**lcm(1,2,3,..B) % n for B > 2
  833. # it looks weird, but it's right: primes run [2, B]
  834. # and the answer's not right until the loop is done.
  835. for i in range(retries + 1):
  836. aM = a
  837. for p in sieve.primerange(2, B + 1):
  838. e = int(math.log(B, p))
  839. aM = pow(aM, pow(p, e), n)
  840. g = gcd(aM - 1, n)
  841. if 1 < g < n:
  842. return int(g)
  843. # get a new a:
  844. # since the exponent, lcm(1..B), is even, if we allow 'a' to be 'n-1'
  845. # then (n - 1)**even % n will be 1 which will give a g of 0 and 1 will
  846. # give a zero, too, so we set the range as [2, n-2]. Some references
  847. # say 'a' should be coprime to n, but either will detect factors.
  848. a = randint(2, n - 2)
  849. def _trial(factors, n, candidates, verbose=False):
  850. """
  851. Helper function for integer factorization. Trial factors ``n`
  852. against all integers given in the sequence ``candidates``
  853. and updates the dict ``factors`` in-place. Returns the reduced
  854. value of ``n`` and a flag indicating whether any factors were found.
  855. """
  856. if verbose:
  857. factors0 = list(factors.keys())
  858. nfactors = len(factors)
  859. for d in candidates:
  860. if n % d == 0:
  861. if n != d:
  862. factor_cache[n] = d
  863. n, m = remove(n // d, d)
  864. factors[d] = m + 1
  865. if verbose:
  866. for k in sorted(set(factors).difference(set(factors0))):
  867. print(factor_msg % (k, factors[k]))
  868. return int(n), len(factors) != nfactors
  869. def _check_termination(factors, n, limit, use_trial, use_rho, use_pm1,
  870. verbose, next_p):
  871. """
  872. Helper function for integer factorization. Checks if ``n``
  873. is a prime or a perfect power, and in those cases updates the factorization.
  874. """
  875. if verbose:
  876. print('Check for termination')
  877. if n == 1:
  878. if verbose:
  879. print(complete_msg)
  880. return True
  881. if n < next_p**2 or isprime(n):
  882. factor_cache[n] = n
  883. factors[int(n)] = 1
  884. if verbose:
  885. print(complete_msg)
  886. return True
  887. # since we've already been factoring there is no need to do
  888. # simultaneous factoring with the power check
  889. p = _perfect_power(n, next_p)
  890. if not p:
  891. return False
  892. base, exp = p
  893. if base < next_p**2 or isprime(base):
  894. factor_cache[n] = base
  895. factors[base] = exp
  896. else:
  897. facs = factorint(base, limit, use_trial, use_rho, use_pm1,
  898. verbose=False)
  899. for b, e in facs.items():
  900. if verbose:
  901. print(factor_msg % (b, e))
  902. factors[b] = exp*e
  903. if verbose:
  904. print(complete_msg)
  905. return True
  906. trial_int_msg = "Trial division with ints [%i ... %i] and fail_max=%i"
  907. trial_msg = "Trial division with primes [%i ... %i]"
  908. rho_msg = "Pollard's rho with retries %i, max_steps %i and seed %i"
  909. pm1_msg = "Pollard's p-1 with smoothness bound %i and seed %i"
  910. ecm_msg = "Elliptic Curve with B1 bound %i, B2 bound %i, num_curves %i"
  911. factor_msg = '\t%i ** %i'
  912. fermat_msg = 'Close factors satisfying Fermat condition found.'
  913. complete_msg = 'Factorization is complete.'
  914. def _factorint_small(factors, n, limit, fail_max, next_p=2):
  915. """
  916. Return the value of n and either a 0 (indicating that factorization up
  917. to the limit was complete) or else the next near-prime that would have
  918. been tested.
  919. Factoring stops if there are fail_max unsuccessful tests in a row.
  920. If factors of n were found they will be in the factors dictionary as
  921. {factor: multiplicity} and the returned value of n will have had those
  922. factors removed. The factors dictionary is modified in-place.
  923. """
  924. def done(n, d):
  925. """return n, d if the sqrt(n) was not reached yet, else
  926. n, 0 indicating that factoring is done.
  927. """
  928. if d*d <= n:
  929. return n, d
  930. return n, 0
  931. limit2 = limit**2
  932. threshold2 = min(n, limit2)
  933. if next_p < 3:
  934. if not n & 1:
  935. m = bit_scan1(n)
  936. factors[2] = m
  937. n >>= m
  938. threshold2 = min(n, limit2)
  939. next_p = 3
  940. if threshold2 < 9: # next_p**2 = 9
  941. return done(n, next_p)
  942. if next_p < 5:
  943. if not n % 3:
  944. n //= 3
  945. m = 1
  946. while not n % 3:
  947. n //= 3
  948. m += 1
  949. if m == 20:
  950. n, mm = remove(n, 3)
  951. m += mm
  952. break
  953. factors[3] = m
  954. threshold2 = min(n, limit2)
  955. next_p = 5
  956. if threshold2 < 25: # next_p**2 = 25
  957. return done(n, next_p)
  958. # Because of the order of checks, starting from `min_p = 6k+5`,
  959. # useless checks are caused.
  960. # We want to calculate
  961. # next_p += [-1, -2, 3, 2, 1, 0][next_p % 6]
  962. p6 = next_p % 6
  963. next_p += (-1 if p6 < 2 else 5) - p6
  964. fails = 0
  965. while fails < fail_max:
  966. # next_p % 6 == 5
  967. if n % next_p:
  968. fails += 1
  969. else:
  970. n //= next_p
  971. m = 1
  972. while not n % next_p:
  973. n //= next_p
  974. m += 1
  975. if m == 20:
  976. n, mm = remove(n, next_p)
  977. m += mm
  978. break
  979. factors[next_p] = m
  980. fails = 0
  981. threshold2 = min(n, limit2)
  982. next_p += 2
  983. if threshold2 < next_p**2:
  984. return done(n, next_p)
  985. # next_p % 6 == 1
  986. if n % next_p:
  987. fails += 1
  988. else:
  989. n //= next_p
  990. m = 1
  991. while not n % next_p:
  992. n //= next_p
  993. m += 1
  994. if m == 20:
  995. n, mm = remove(n, next_p)
  996. m += mm
  997. break
  998. factors[next_p] = m
  999. fails = 0
  1000. threshold2 = min(n, limit2)
  1001. next_p += 4
  1002. if threshold2 < next_p**2:
  1003. return done(n, next_p)
  1004. return done(n, next_p)
  1005. def factorint(n, limit=None, use_trial=True, use_rho=True, use_pm1=True,
  1006. use_ecm=True, verbose=False, visual=None, multiple=False):
  1007. r"""
  1008. Given a positive integer ``n``, ``factorint(n)`` returns a dict containing
  1009. the prime factors of ``n`` as keys and their respective multiplicities
  1010. as values. For example:
  1011. >>> from sympy.ntheory import factorint
  1012. >>> factorint(2000) # 2000 = (2**4) * (5**3)
  1013. {2: 4, 5: 3}
  1014. >>> factorint(65537) # This number is prime
  1015. {65537: 1}
  1016. For input less than 2, factorint behaves as follows:
  1017. - ``factorint(1)`` returns the empty factorization, ``{}``
  1018. - ``factorint(0)`` returns ``{0:1}``
  1019. - ``factorint(-n)`` adds ``-1:1`` to the factors and then factors ``n``
  1020. Partial Factorization:
  1021. If ``limit`` (> 3) is specified, the search is stopped after performing
  1022. trial division up to (and including) the limit (or taking a
  1023. corresponding number of rho/p-1 steps). This is useful if one has
  1024. a large number and only is interested in finding small factors (if
  1025. any). Note that setting a limit does not prevent larger factors
  1026. from being found early; it simply means that the largest factor may
  1027. be composite. Since checking for perfect power is relatively cheap, it is
  1028. done regardless of the limit setting.
  1029. This number, for example, has two small factors and a huge
  1030. semi-prime factor that cannot be reduced easily:
  1031. >>> from sympy.ntheory import isprime
  1032. >>> a = 1407633717262338957430697921446883
  1033. >>> f = factorint(a, limit=10000)
  1034. >>> f == {991: 1, int(202916782076162456022877024859): 1, 7: 1}
  1035. True
  1036. >>> isprime(max(f))
  1037. False
  1038. This number has a small factor and a residual perfect power whose
  1039. base is greater than the limit:
  1040. >>> factorint(3*101**7, limit=5)
  1041. {3: 1, 101: 7}
  1042. List of Factors:
  1043. If ``multiple`` is set to ``True`` then a list containing the
  1044. prime factors including multiplicities is returned.
  1045. >>> factorint(24, multiple=True)
  1046. [2, 2, 2, 3]
  1047. Visual Factorization:
  1048. If ``visual`` is set to ``True``, then it will return a visual
  1049. factorization of the integer. For example:
  1050. >>> from sympy import pprint
  1051. >>> pprint(factorint(4200, visual=True))
  1052. 3 1 2 1
  1053. 2 *3 *5 *7
  1054. Note that this is achieved by using the evaluate=False flag in Mul
  1055. and Pow. If you do other manipulations with an expression where
  1056. evaluate=False, it may evaluate. Therefore, you should use the
  1057. visual option only for visualization, and use the normal dictionary
  1058. returned by visual=False if you want to perform operations on the
  1059. factors.
  1060. You can easily switch between the two forms by sending them back to
  1061. factorint:
  1062. >>> from sympy import Mul
  1063. >>> regular = factorint(1764); regular
  1064. {2: 2, 3: 2, 7: 2}
  1065. >>> pprint(factorint(regular))
  1066. 2 2 2
  1067. 2 *3 *7
  1068. >>> visual = factorint(1764, visual=True); pprint(visual)
  1069. 2 2 2
  1070. 2 *3 *7
  1071. >>> print(factorint(visual))
  1072. {2: 2, 3: 2, 7: 2}
  1073. If you want to send a number to be factored in a partially factored form
  1074. you can do so with a dictionary or unevaluated expression:
  1075. >>> factorint(factorint({4: 2, 12: 3})) # twice to toggle to dict form
  1076. {2: 10, 3: 3}
  1077. >>> factorint(Mul(4, 12, evaluate=False))
  1078. {2: 4, 3: 1}
  1079. The table of the output logic is:
  1080. ====== ====== ======= =======
  1081. Visual
  1082. ------ ----------------------
  1083. Input True False other
  1084. ====== ====== ======= =======
  1085. dict mul dict mul
  1086. n mul dict dict
  1087. mul mul dict dict
  1088. ====== ====== ======= =======
  1089. Notes
  1090. =====
  1091. Algorithm:
  1092. The function switches between multiple algorithms. Trial division
  1093. quickly finds small factors (of the order 1-5 digits), and finds
  1094. all large factors if given enough time. The Pollard rho and p-1
  1095. algorithms are used to find large factors ahead of time; they
  1096. will often find factors of the order of 10 digits within a few
  1097. seconds:
  1098. >>> factors = factorint(12345678910111213141516)
  1099. >>> for base, exp in sorted(factors.items()):
  1100. ... print('%s %s' % (base, exp))
  1101. ...
  1102. 2 2
  1103. 2507191691 1
  1104. 1231026625769 1
  1105. Any of these methods can optionally be disabled with the following
  1106. boolean parameters:
  1107. - ``use_trial``: Toggle use of trial division
  1108. - ``use_rho``: Toggle use of Pollard's rho method
  1109. - ``use_pm1``: Toggle use of Pollard's p-1 method
  1110. ``factorint`` also periodically checks if the remaining part is
  1111. a prime number or a perfect power, and in those cases stops.
  1112. For unevaluated factorial, it uses Legendre's formula(theorem).
  1113. If ``verbose`` is set to ``True``, detailed progress is printed.
  1114. See Also
  1115. ========
  1116. smoothness, smoothness_p, divisors
  1117. """
  1118. if isinstance(n, Dict):
  1119. n = dict(n)
  1120. if multiple:
  1121. fac = factorint(n, limit=limit, use_trial=use_trial,
  1122. use_rho=use_rho, use_pm1=use_pm1,
  1123. verbose=verbose, visual=False, multiple=False)
  1124. factorlist = sum(([p] * fac[p] if fac[p] > 0 else [S.One/p]*(-fac[p])
  1125. for p in sorted(fac)), [])
  1126. return factorlist
  1127. factordict = {}
  1128. if visual and not isinstance(n, (Mul, dict)):
  1129. factordict = factorint(n, limit=limit, use_trial=use_trial,
  1130. use_rho=use_rho, use_pm1=use_pm1,
  1131. verbose=verbose, visual=False)
  1132. elif isinstance(n, Mul):
  1133. factordict = {int(k): int(v) for k, v in
  1134. n.as_powers_dict().items()}
  1135. elif isinstance(n, dict):
  1136. factordict = n
  1137. if factordict and isinstance(n, (Mul, dict)):
  1138. # check it
  1139. for key in list(factordict.keys()):
  1140. if isprime(key):
  1141. continue
  1142. e = factordict.pop(key)
  1143. d = factorint(key, limit=limit, use_trial=use_trial, use_rho=use_rho,
  1144. use_pm1=use_pm1, verbose=verbose, visual=False)
  1145. for k, v in d.items():
  1146. if k in factordict:
  1147. factordict[k] += v*e
  1148. else:
  1149. factordict[k] = v*e
  1150. if visual or (type(n) is dict and
  1151. visual is not True and
  1152. visual is not False):
  1153. if factordict == {}:
  1154. return S.One
  1155. if -1 in factordict:
  1156. factordict.pop(-1)
  1157. args = [S.NegativeOne]
  1158. else:
  1159. args = []
  1160. args.extend([Pow(*i, evaluate=False)
  1161. for i in sorted(factordict.items())])
  1162. return Mul(*args, evaluate=False)
  1163. elif isinstance(n, (dict, Mul)):
  1164. return factordict
  1165. assert use_trial or use_rho or use_pm1 or use_ecm
  1166. from sympy.functions.combinatorial.factorials import factorial
  1167. if isinstance(n, factorial):
  1168. x = as_int(n.args[0])
  1169. if x >= 20:
  1170. factors = {}
  1171. m = 2 # to initialize the if condition below
  1172. for p in sieve.primerange(2, x + 1):
  1173. if m > 1:
  1174. m, q = 0, x // p
  1175. while q != 0:
  1176. m += q
  1177. q //= p
  1178. factors[p] = m
  1179. if factors and verbose:
  1180. for k in sorted(factors):
  1181. print(factor_msg % (k, factors[k]))
  1182. if verbose:
  1183. print(complete_msg)
  1184. return factors
  1185. else:
  1186. # if n < 20!, direct computation is faster
  1187. # since it uses a lookup table
  1188. n = n.func(x)
  1189. n = as_int(n)
  1190. if limit:
  1191. limit = int(limit)
  1192. use_ecm = False
  1193. # special cases
  1194. if n < 0:
  1195. factors = factorint(
  1196. -n, limit=limit, use_trial=use_trial, use_rho=use_rho,
  1197. use_pm1=use_pm1, verbose=verbose, visual=False)
  1198. factors[-1] = 1
  1199. return factors
  1200. if limit and limit < 2:
  1201. if n == 1:
  1202. return {}
  1203. return {n: 1}
  1204. elif n < 10:
  1205. # doing this we are assured of getting a limit > 2
  1206. # when we have to compute it later
  1207. return [{0: 1}, {}, {2: 1}, {3: 1}, {2: 2}, {5: 1},
  1208. {2: 1, 3: 1}, {7: 1}, {2: 3}, {3: 2}][n]
  1209. factors = {}
  1210. # do simplistic factorization
  1211. if verbose:
  1212. sn = str(n)
  1213. if len(sn) > 50:
  1214. print('Factoring %s' % sn[:5] + \
  1215. '..(%i other digits)..' % (len(sn) - 10) + sn[-5:])
  1216. else:
  1217. print('Factoring', n)
  1218. # this is the preliminary factorization for small factors
  1219. # We want to guarantee that there are no small prime factors,
  1220. # so we run even if `use_trial` is False.
  1221. small = 2**15
  1222. fail_max = 600
  1223. small = min(small, limit or small)
  1224. if verbose:
  1225. print(trial_int_msg % (2, small, fail_max))
  1226. n, next_p = _factorint_small(factors, n, small, fail_max)
  1227. if factors and verbose:
  1228. for k in sorted(factors):
  1229. print(factor_msg % (k, factors[k]))
  1230. if next_p == 0:
  1231. if n > 1:
  1232. factors[int(n)] = 1
  1233. if verbose:
  1234. print(complete_msg)
  1235. return factors
  1236. # Check if it exists in the cache
  1237. while p := factor_cache.get(n):
  1238. n, e = remove(n, p)
  1239. factors[int(p)] = int(e)
  1240. # first check if the simplistic run didn't finish
  1241. # because of the limit and check for a perfect
  1242. # power before exiting
  1243. if limit and next_p > limit:
  1244. if verbose:
  1245. print('Exceeded limit:', limit)
  1246. if _check_termination(factors, n, limit, use_trial,
  1247. use_rho, use_pm1, verbose, next_p):
  1248. return factors
  1249. if n > 1:
  1250. factors[int(n)] = 1
  1251. return factors
  1252. if _check_termination(factors, n, limit, use_trial,
  1253. use_rho, use_pm1, verbose, next_p):
  1254. return factors
  1255. # continue with more advanced factorization methods
  1256. # ...do a Fermat test since it's so easy and we need the
  1257. # square root anyway. Finding 2 factors is easy if they are
  1258. # "close enough." This is the big root equivalent of dividing by
  1259. # 2, 3, 5.
  1260. sqrt_n = isqrt(n)
  1261. a = sqrt_n + 1
  1262. # If `n % 4 == 1`, `a` must be odd for `a**2 - n` to be a square number.
  1263. if (n % 4 == 1) ^ (a & 1):
  1264. a += 1
  1265. a2 = a**2
  1266. b2 = a2 - n
  1267. for _ in range(3):
  1268. b, fermat = sqrtrem(b2)
  1269. if not fermat:
  1270. if verbose:
  1271. print(fermat_msg)
  1272. for r in [a - b, a + b]:
  1273. facs = factorint(r, limit=limit, use_trial=use_trial,
  1274. use_rho=use_rho, use_pm1=use_pm1,
  1275. verbose=verbose)
  1276. for k, v in facs.items():
  1277. factors[k] = factors.get(k, 0) + v
  1278. factor_cache.add(n, facs)
  1279. if verbose:
  1280. print(complete_msg)
  1281. return factors
  1282. b2 += (a + 1) << 2 # equiv to (a + 2)**2 - n
  1283. a += 2
  1284. # these are the limits for trial division which will
  1285. # be attempted in parallel with pollard methods
  1286. low, high = next_p, 2*next_p
  1287. # add 1 to make sure limit is reached in primerange calls
  1288. _limit = (limit or sqrt_n) + 1
  1289. iteration = 0
  1290. while 1:
  1291. high_ = min(high, _limit)
  1292. # Trial division
  1293. if use_trial:
  1294. if verbose:
  1295. print(trial_msg % (low, high_))
  1296. ps = sieve.primerange(low, high_)
  1297. n, found_trial = _trial(factors, n, ps, verbose)
  1298. next_p = high_
  1299. if found_trial and _check_termination(factors, n, limit, use_trial,
  1300. use_rho, use_pm1, verbose, next_p):
  1301. return factors
  1302. else:
  1303. found_trial = False
  1304. if high > _limit:
  1305. if verbose:
  1306. print('Exceeded limit:', _limit)
  1307. if n > 1:
  1308. factors[int(n)] = 1
  1309. if verbose:
  1310. print(complete_msg)
  1311. return factors
  1312. # Only used advanced methods when no small factors were found
  1313. if not found_trial:
  1314. # Pollard p-1
  1315. if use_pm1:
  1316. if verbose:
  1317. print(pm1_msg % (low, high_))
  1318. c = pollard_pm1(n, B=low, seed=high_)
  1319. if c:
  1320. if c < next_p**2 or isprime(c):
  1321. ps = [c]
  1322. else:
  1323. ps = factorint(c, limit=limit,
  1324. use_trial=use_trial,
  1325. use_rho=use_rho,
  1326. use_pm1=use_pm1,
  1327. use_ecm=use_ecm,
  1328. verbose=verbose)
  1329. n, _ = _trial(factors, n, ps, verbose=False)
  1330. if _check_termination(factors, n, limit, use_trial,
  1331. use_rho, use_pm1, verbose, next_p):
  1332. return factors
  1333. # Pollard rho
  1334. if use_rho:
  1335. if verbose:
  1336. print(rho_msg % (1, low, high_))
  1337. c = pollard_rho(n, retries=1, max_steps=low, seed=high_)
  1338. if c:
  1339. if c < next_p**2 or isprime(c):
  1340. ps = [c]
  1341. else:
  1342. ps = factorint(c, limit=limit,
  1343. use_trial=use_trial,
  1344. use_rho=use_rho,
  1345. use_pm1=use_pm1,
  1346. use_ecm=use_ecm,
  1347. verbose=verbose)
  1348. n, _ = _trial(factors, n, ps, verbose=False)
  1349. if _check_termination(factors, n, limit, use_trial,
  1350. use_rho, use_pm1, verbose, next_p):
  1351. return factors
  1352. # Use subexponential algorithms if use_ecm
  1353. # Use pollard algorithms for finding small factors for 3 iterations
  1354. # if after small factors the number of digits of n >= 25 then use ecm
  1355. iteration += 1
  1356. if use_ecm and iteration >= 3 and num_digits(n) >= 24:
  1357. break
  1358. low, high = high, high*2
  1359. B1 = 10000
  1360. B2 = 100*B1
  1361. num_curves = 50
  1362. while(1):
  1363. if verbose:
  1364. print(ecm_msg % (B1, B2, num_curves))
  1365. factor = _ecm_one_factor(n, B1, B2, num_curves, seed=B1)
  1366. if factor:
  1367. if factor < next_p**2 or isprime(factor):
  1368. ps = [factor]
  1369. else:
  1370. ps = factorint(factor, limit=limit,
  1371. use_trial=use_trial,
  1372. use_rho=use_rho,
  1373. use_pm1=use_pm1,
  1374. use_ecm=use_ecm,
  1375. verbose=verbose)
  1376. n, _ = _trial(factors, n, ps, verbose=False)
  1377. if _check_termination(factors, n, limit, use_trial,
  1378. use_rho, use_pm1, verbose, next_p):
  1379. return factors
  1380. B1 *= 5
  1381. B2 = 100*B1
  1382. num_curves *= 4
  1383. def factorrat(rat, limit=None, use_trial=True, use_rho=True, use_pm1=True,
  1384. verbose=False, visual=None, multiple=False):
  1385. r"""
  1386. Given a Rational ``r``, ``factorrat(r)`` returns a dict containing
  1387. the prime factors of ``r`` as keys and their respective multiplicities
  1388. as values. For example:
  1389. >>> from sympy import factorrat, S
  1390. >>> factorrat(S(8)/9) # 8/9 = (2**3) * (3**-2)
  1391. {2: 3, 3: -2}
  1392. >>> factorrat(S(-1)/987) # -1/789 = -1 * (3**-1) * (7**-1) * (47**-1)
  1393. {-1: 1, 3: -1, 7: -1, 47: -1}
  1394. Please see the docstring for ``factorint`` for detailed explanations
  1395. and examples of the following keywords:
  1396. - ``limit``: Integer limit up to which trial division is done
  1397. - ``use_trial``: Toggle use of trial division
  1398. - ``use_rho``: Toggle use of Pollard's rho method
  1399. - ``use_pm1``: Toggle use of Pollard's p-1 method
  1400. - ``verbose``: Toggle detailed printing of progress
  1401. - ``multiple``: Toggle returning a list of factors or dict
  1402. - ``visual``: Toggle product form of output
  1403. """
  1404. if multiple:
  1405. fac = factorrat(rat, limit=limit, use_trial=use_trial,
  1406. use_rho=use_rho, use_pm1=use_pm1,
  1407. verbose=verbose, visual=False, multiple=False)
  1408. factorlist = sum(([p] * fac[p] if fac[p] > 0 else [S.One/p]*(-fac[p])
  1409. for p, _ in sorted(fac.items(),
  1410. key=lambda elem: elem[0]
  1411. if elem[1] > 0
  1412. else 1/elem[0])), [])
  1413. return factorlist
  1414. f = factorint(rat.p, limit=limit, use_trial=use_trial,
  1415. use_rho=use_rho, use_pm1=use_pm1,
  1416. verbose=verbose).copy()
  1417. f = defaultdict(int, f)
  1418. for p, e in factorint(rat.q, limit=limit,
  1419. use_trial=use_trial,
  1420. use_rho=use_rho,
  1421. use_pm1=use_pm1,
  1422. verbose=verbose).items():
  1423. f[p] += -e
  1424. if len(f) > 1 and 1 in f:
  1425. del f[1]
  1426. if not visual:
  1427. return dict(f)
  1428. else:
  1429. if -1 in f:
  1430. f.pop(-1)
  1431. args = [S.NegativeOne]
  1432. else:
  1433. args = []
  1434. args.extend([Pow(*i, evaluate=False)
  1435. for i in sorted(f.items())])
  1436. return Mul(*args, evaluate=False)
  1437. def primefactors(n, limit=None, verbose=False, **kwargs):
  1438. """Return a sorted list of n's prime factors, ignoring multiplicity
  1439. and any composite factor that remains if the limit was set too low
  1440. for complete factorization. Unlike factorint(), primefactors() does
  1441. not return -1 or 0.
  1442. Parameters
  1443. ==========
  1444. n : integer
  1445. limit, verbose, **kwargs :
  1446. Additional keyword arguments to be passed to ``factorint``.
  1447. Since ``kwargs`` is new in version 1.13,
  1448. ``limit`` and ``verbose`` are retained for compatibility purposes.
  1449. Returns
  1450. =======
  1451. list(int) : List of prime numbers dividing ``n``
  1452. Examples
  1453. ========
  1454. >>> from sympy.ntheory import primefactors, factorint, isprime
  1455. >>> primefactors(6)
  1456. [2, 3]
  1457. >>> primefactors(-5)
  1458. [5]
  1459. >>> sorted(factorint(123456).items())
  1460. [(2, 6), (3, 1), (643, 1)]
  1461. >>> primefactors(123456)
  1462. [2, 3, 643]
  1463. >>> sorted(factorint(10000000001, limit=200).items())
  1464. [(101, 1), (99009901, 1)]
  1465. >>> isprime(99009901)
  1466. False
  1467. >>> primefactors(10000000001, limit=300)
  1468. [101]
  1469. See Also
  1470. ========
  1471. factorint, divisors
  1472. """
  1473. n = int(n)
  1474. kwargs.update({"visual": None, "multiple": False,
  1475. "limit": limit, "verbose": verbose})
  1476. factors = sorted(factorint(n=n, **kwargs).keys())
  1477. # We want to calculate
  1478. # s = [f for f in factors if isprime(f)]
  1479. s = [f for f in factors[:-1:] if f not in [-1, 0, 1]]
  1480. if factors and isprime(factors[-1]):
  1481. s += [factors[-1]]
  1482. return s
  1483. def _divisors(n, proper=False):
  1484. """Helper function for divisors which generates the divisors.
  1485. Parameters
  1486. ==========
  1487. n : int
  1488. a nonnegative integer
  1489. proper: bool
  1490. If `True`, returns the generator that outputs only the proper divisor (i.e., excluding n).
  1491. """
  1492. if n <= 1:
  1493. if not proper and n:
  1494. yield 1
  1495. return
  1496. factordict = factorint(n)
  1497. ps = sorted(factordict.keys())
  1498. def rec_gen(n=0):
  1499. if n == len(ps):
  1500. yield 1
  1501. else:
  1502. pows = [1]
  1503. for _ in range(factordict[ps[n]]):
  1504. pows.append(pows[-1] * ps[n])
  1505. yield from (p * q for q in rec_gen(n + 1) for p in pows)
  1506. if proper:
  1507. yield from (p for p in rec_gen() if p != n)
  1508. else:
  1509. yield from rec_gen()
  1510. def divisors(n, generator=False, proper=False):
  1511. r"""
  1512. Return all divisors of n sorted from 1..n by default.
  1513. If generator is ``True`` an unordered generator is returned.
  1514. The number of divisors of n can be quite large if there are many
  1515. prime factors (counting repeated factors). If only the number of
  1516. factors is desired use divisor_count(n).
  1517. Examples
  1518. ========
  1519. >>> from sympy import divisors, divisor_count
  1520. >>> divisors(24)
  1521. [1, 2, 3, 4, 6, 8, 12, 24]
  1522. >>> divisor_count(24)
  1523. 8
  1524. >>> list(divisors(120, generator=True))
  1525. [1, 2, 4, 8, 3, 6, 12, 24, 5, 10, 20, 40, 15, 30, 60, 120]
  1526. Notes
  1527. =====
  1528. This is a slightly modified version of Tim Peters referenced at:
  1529. https://stackoverflow.com/questions/1010381/python-factorization
  1530. See Also
  1531. ========
  1532. primefactors, factorint, divisor_count
  1533. """
  1534. rv = _divisors(as_int(abs(n)), proper)
  1535. return rv if generator else sorted(rv)
  1536. def divisor_count(n, modulus=1, proper=False):
  1537. """
  1538. Return the number of divisors of ``n``. If ``modulus`` is not 1 then only
  1539. those that are divisible by ``modulus`` are counted. If ``proper`` is True
  1540. then the divisor of ``n`` will not be counted.
  1541. Examples
  1542. ========
  1543. >>> from sympy import divisor_count
  1544. >>> divisor_count(6)
  1545. 4
  1546. >>> divisor_count(6, 2)
  1547. 2
  1548. >>> divisor_count(6, proper=True)
  1549. 3
  1550. See Also
  1551. ========
  1552. factorint, divisors, totient, proper_divisor_count
  1553. """
  1554. if not modulus:
  1555. return 0
  1556. elif modulus != 1:
  1557. n, r = divmod(n, modulus)
  1558. if r:
  1559. return 0
  1560. if n == 0:
  1561. return 0
  1562. n = Mul(*[v + 1 for k, v in factorint(n).items() if k > 1])
  1563. if n and proper:
  1564. n -= 1
  1565. return n
  1566. def proper_divisors(n, generator=False):
  1567. """
  1568. Return all divisors of n except n, sorted by default.
  1569. If generator is ``True`` an unordered generator is returned.
  1570. Examples
  1571. ========
  1572. >>> from sympy import proper_divisors, proper_divisor_count
  1573. >>> proper_divisors(24)
  1574. [1, 2, 3, 4, 6, 8, 12]
  1575. >>> proper_divisor_count(24)
  1576. 7
  1577. >>> list(proper_divisors(120, generator=True))
  1578. [1, 2, 4, 8, 3, 6, 12, 24, 5, 10, 20, 40, 15, 30, 60]
  1579. See Also
  1580. ========
  1581. factorint, divisors, proper_divisor_count
  1582. """
  1583. return divisors(n, generator=generator, proper=True)
  1584. def proper_divisor_count(n, modulus=1):
  1585. """
  1586. Return the number of proper divisors of ``n``.
  1587. Examples
  1588. ========
  1589. >>> from sympy import proper_divisor_count
  1590. >>> proper_divisor_count(6)
  1591. 3
  1592. >>> proper_divisor_count(6, modulus=2)
  1593. 1
  1594. See Also
  1595. ========
  1596. divisors, proper_divisors, divisor_count
  1597. """
  1598. return divisor_count(n, modulus=modulus, proper=True)
  1599. def _udivisors(n):
  1600. """Helper function for udivisors which generates the unitary divisors.
  1601. Parameters
  1602. ==========
  1603. n : int
  1604. a nonnegative integer
  1605. """
  1606. if n <= 1:
  1607. if n == 1:
  1608. yield 1
  1609. return
  1610. factorpows = [p**e for p, e in factorint(n).items()]
  1611. # We want to calculate
  1612. # yield from (math.prod(s) for s in powersets(factorpows))
  1613. for i in range(2**len(factorpows)):
  1614. d = 1
  1615. for k in range(i.bit_length()):
  1616. if i & 1:
  1617. d *= factorpows[k]
  1618. i >>= 1
  1619. yield d
  1620. def udivisors(n, generator=False):
  1621. r"""
  1622. Return all unitary divisors of n sorted from 1..n by default.
  1623. If generator is ``True`` an unordered generator is returned.
  1624. The number of unitary divisors of n can be quite large if there are many
  1625. prime factors. If only the number of unitary divisors is desired use
  1626. udivisor_count(n).
  1627. Examples
  1628. ========
  1629. >>> from sympy.ntheory.factor_ import udivisors, udivisor_count
  1630. >>> udivisors(15)
  1631. [1, 3, 5, 15]
  1632. >>> udivisor_count(15)
  1633. 4
  1634. >>> sorted(udivisors(120, generator=True))
  1635. [1, 3, 5, 8, 15, 24, 40, 120]
  1636. See Also
  1637. ========
  1638. primefactors, factorint, divisors, divisor_count, udivisor_count
  1639. References
  1640. ==========
  1641. .. [1] https://en.wikipedia.org/wiki/Unitary_divisor
  1642. .. [2] https://mathworld.wolfram.com/UnitaryDivisor.html
  1643. """
  1644. rv = _udivisors(as_int(abs(n)))
  1645. return rv if generator else sorted(rv)
  1646. def udivisor_count(n):
  1647. """
  1648. Return the number of unitary divisors of ``n``.
  1649. Parameters
  1650. ==========
  1651. n : integer
  1652. Examples
  1653. ========
  1654. >>> from sympy.ntheory.factor_ import udivisor_count
  1655. >>> udivisor_count(120)
  1656. 8
  1657. See Also
  1658. ========
  1659. factorint, divisors, udivisors, divisor_count, totient
  1660. References
  1661. ==========
  1662. .. [1] https://mathworld.wolfram.com/UnitaryDivisorFunction.html
  1663. """
  1664. if n == 0:
  1665. return 0
  1666. return 2**len([p for p in factorint(n) if p > 1])
  1667. def _antidivisors(n):
  1668. """Helper function for antidivisors which generates the antidivisors.
  1669. Parameters
  1670. ==========
  1671. n : int
  1672. a nonnegative integer
  1673. """
  1674. if n <= 2:
  1675. return
  1676. for d in _divisors(n):
  1677. y = 2*d
  1678. if n > y and n % y:
  1679. yield y
  1680. for d in _divisors(2*n-1):
  1681. if n > d >= 2 and n % d:
  1682. yield d
  1683. for d in _divisors(2*n+1):
  1684. if n > d >= 2 and n % d:
  1685. yield d
  1686. def antidivisors(n, generator=False):
  1687. r"""
  1688. Return all antidivisors of n sorted from 1..n by default.
  1689. Antidivisors [1]_ of n are numbers that do not divide n by the largest
  1690. possible margin. If generator is True an unordered generator is returned.
  1691. Examples
  1692. ========
  1693. >>> from sympy.ntheory.factor_ import antidivisors
  1694. >>> antidivisors(24)
  1695. [7, 16]
  1696. >>> sorted(antidivisors(128, generator=True))
  1697. [3, 5, 15, 17, 51, 85]
  1698. See Also
  1699. ========
  1700. primefactors, factorint, divisors, divisor_count, antidivisor_count
  1701. References
  1702. ==========
  1703. .. [1] definition is described in https://oeis.org/A066272/a066272a.html
  1704. """
  1705. rv = _antidivisors(as_int(abs(n)))
  1706. return rv if generator else sorted(rv)
  1707. def antidivisor_count(n):
  1708. """
  1709. Return the number of antidivisors [1]_ of ``n``.
  1710. Parameters
  1711. ==========
  1712. n : integer
  1713. Examples
  1714. ========
  1715. >>> from sympy.ntheory.factor_ import antidivisor_count
  1716. >>> antidivisor_count(13)
  1717. 4
  1718. >>> antidivisor_count(27)
  1719. 5
  1720. See Also
  1721. ========
  1722. factorint, divisors, antidivisors, divisor_count, totient
  1723. References
  1724. ==========
  1725. .. [1] formula from https://oeis.org/A066272
  1726. """
  1727. n = as_int(abs(n))
  1728. if n <= 2:
  1729. return 0
  1730. return divisor_count(2*n - 1) + divisor_count(2*n + 1) + \
  1731. divisor_count(n) - divisor_count(n, 2) - 5
  1732. @deprecated("""\
  1733. The `sympy.ntheory.factor_.totient` has been moved to `sympy.functions.combinatorial.numbers.totient`.""",
  1734. deprecated_since_version="1.13",
  1735. active_deprecations_target='deprecated-ntheory-symbolic-functions')
  1736. def totient(n):
  1737. r"""
  1738. Calculate the Euler totient function phi(n)
  1739. .. deprecated:: 1.13
  1740. The ``totient`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.totient`
  1741. instead. See its documentation for more information. See
  1742. :ref:`deprecated-ntheory-symbolic-functions` for details.
  1743. ``totient(n)`` or `\phi(n)` is the number of positive integers `\leq` n
  1744. that are relatively prime to n.
  1745. Parameters
  1746. ==========
  1747. n : integer
  1748. Examples
  1749. ========
  1750. >>> from sympy.functions.combinatorial.numbers import totient
  1751. >>> totient(1)
  1752. 1
  1753. >>> totient(25)
  1754. 20
  1755. >>> totient(45) == totient(5)*totient(9)
  1756. True
  1757. See Also
  1758. ========
  1759. divisor_count
  1760. References
  1761. ==========
  1762. .. [1] https://en.wikipedia.org/wiki/Euler%27s_totient_function
  1763. .. [2] https://mathworld.wolfram.com/TotientFunction.html
  1764. """
  1765. from sympy.functions.combinatorial.numbers import totient as _totient
  1766. return _totient(n)
  1767. @deprecated("""\
  1768. The `sympy.ntheory.factor_.reduced_totient` has been moved to `sympy.functions.combinatorial.numbers.reduced_totient`.""",
  1769. deprecated_since_version="1.13",
  1770. active_deprecations_target='deprecated-ntheory-symbolic-functions')
  1771. def reduced_totient(n):
  1772. r"""
  1773. Calculate the Carmichael reduced totient function lambda(n)
  1774. .. deprecated:: 1.13
  1775. The ``reduced_totient`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.reduced_totient`
  1776. instead. See its documentation for more information. See
  1777. :ref:`deprecated-ntheory-symbolic-functions` for details.
  1778. ``reduced_totient(n)`` or `\lambda(n)` is the smallest m > 0 such that
  1779. `k^m \equiv 1 \mod n` for all k relatively prime to n.
  1780. Examples
  1781. ========
  1782. >>> from sympy.functions.combinatorial.numbers import reduced_totient
  1783. >>> reduced_totient(1)
  1784. 1
  1785. >>> reduced_totient(8)
  1786. 2
  1787. >>> reduced_totient(30)
  1788. 4
  1789. See Also
  1790. ========
  1791. totient
  1792. References
  1793. ==========
  1794. .. [1] https://en.wikipedia.org/wiki/Carmichael_function
  1795. .. [2] https://mathworld.wolfram.com/CarmichaelFunction.html
  1796. """
  1797. from sympy.functions.combinatorial.numbers import reduced_totient as _reduced_totient
  1798. return _reduced_totient(n)
  1799. @deprecated("""\
  1800. The `sympy.ntheory.factor_.divisor_sigma` has been moved to `sympy.functions.combinatorial.numbers.divisor_sigma`.""",
  1801. deprecated_since_version="1.13",
  1802. active_deprecations_target='deprecated-ntheory-symbolic-functions')
  1803. def divisor_sigma(n, k=1):
  1804. r"""
  1805. Calculate the divisor function `\sigma_k(n)` for positive integer n
  1806. .. deprecated:: 1.13
  1807. The ``divisor_sigma`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.divisor_sigma`
  1808. instead. See its documentation for more information. See
  1809. :ref:`deprecated-ntheory-symbolic-functions` for details.
  1810. ``divisor_sigma(n, k)`` is equal to ``sum([x**k for x in divisors(n)])``
  1811. If n's prime factorization is:
  1812. .. math ::
  1813. n = \prod_{i=1}^\omega p_i^{m_i},
  1814. then
  1815. .. math ::
  1816. \sigma_k(n) = \prod_{i=1}^\omega (1+p_i^k+p_i^{2k}+\cdots
  1817. + p_i^{m_ik}).
  1818. Parameters
  1819. ==========
  1820. n : integer
  1821. k : integer, optional
  1822. power of divisors in the sum
  1823. for k = 0, 1:
  1824. ``divisor_sigma(n, 0)`` is equal to ``divisor_count(n)``
  1825. ``divisor_sigma(n, 1)`` is equal to ``sum(divisors(n))``
  1826. Default for k is 1.
  1827. Examples
  1828. ========
  1829. >>> from sympy.functions.combinatorial.numbers import divisor_sigma
  1830. >>> divisor_sigma(18, 0)
  1831. 6
  1832. >>> divisor_sigma(39, 1)
  1833. 56
  1834. >>> divisor_sigma(12, 2)
  1835. 210
  1836. >>> divisor_sigma(37)
  1837. 38
  1838. See Also
  1839. ========
  1840. divisor_count, totient, divisors, factorint
  1841. References
  1842. ==========
  1843. .. [1] https://en.wikipedia.org/wiki/Divisor_function
  1844. """
  1845. from sympy.functions.combinatorial.numbers import divisor_sigma as func_divisor_sigma
  1846. return func_divisor_sigma(n, k)
  1847. def _divisor_sigma(n:int, k:int=1) -> int:
  1848. r""" Calculate the divisor function `\sigma_k(n)` for positive integer n
  1849. Parameters
  1850. ==========
  1851. n : int
  1852. positive integer
  1853. k : int
  1854. nonnegative integer
  1855. See Also
  1856. ========
  1857. sympy.functions.combinatorial.numbers.divisor_sigma
  1858. """
  1859. if k == 0:
  1860. return math.prod(e + 1 for e in factorint(n).values())
  1861. return math.prod((p**(k*(e + 1)) - 1)//(p**k - 1) for p, e in factorint(n).items())
  1862. def core(n, t=2):
  1863. r"""
  1864. Calculate core(n, t) = `core_t(n)` of a positive integer n
  1865. ``core_2(n)`` is equal to the squarefree part of n
  1866. If n's prime factorization is:
  1867. .. math ::
  1868. n = \prod_{i=1}^\omega p_i^{m_i},
  1869. then
  1870. .. math ::
  1871. core_t(n) = \prod_{i=1}^\omega p_i^{m_i \mod t}.
  1872. Parameters
  1873. ==========
  1874. n : integer
  1875. t : integer
  1876. core(n, t) calculates the t-th power free part of n
  1877. ``core(n, 2)`` is the squarefree part of ``n``
  1878. ``core(n, 3)`` is the cubefree part of ``n``
  1879. Default for t is 2.
  1880. Examples
  1881. ========
  1882. >>> from sympy.ntheory.factor_ import core
  1883. >>> core(24, 2)
  1884. 6
  1885. >>> core(9424, 3)
  1886. 1178
  1887. >>> core(379238)
  1888. 379238
  1889. >>> core(15**11, 10)
  1890. 15
  1891. See Also
  1892. ========
  1893. factorint, sympy.solvers.diophantine.diophantine.square_factor
  1894. References
  1895. ==========
  1896. .. [1] https://en.wikipedia.org/wiki/Square-free_integer#Squarefree_core
  1897. """
  1898. n = as_int(n)
  1899. t = as_int(t)
  1900. if n <= 0:
  1901. raise ValueError("n must be a positive integer")
  1902. elif t <= 1:
  1903. raise ValueError("t must be >= 2")
  1904. else:
  1905. y = 1
  1906. for p, e in factorint(n).items():
  1907. y *= p**(e % t)
  1908. return y
  1909. @deprecated("""\
  1910. The `sympy.ntheory.factor_.udivisor_sigma` has been moved to `sympy.functions.combinatorial.numbers.udivisor_sigma`.""",
  1911. deprecated_since_version="1.13",
  1912. active_deprecations_target='deprecated-ntheory-symbolic-functions')
  1913. def udivisor_sigma(n, k=1):
  1914. r"""
  1915. Calculate the unitary divisor function `\sigma_k^*(n)` for positive integer n
  1916. .. deprecated:: 1.13
  1917. The ``udivisor_sigma`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.udivisor_sigma`
  1918. instead. See its documentation for more information. See
  1919. :ref:`deprecated-ntheory-symbolic-functions` for details.
  1920. ``udivisor_sigma(n, k)`` is equal to ``sum([x**k for x in udivisors(n)])``
  1921. If n's prime factorization is:
  1922. .. math ::
  1923. n = \prod_{i=1}^\omega p_i^{m_i},
  1924. then
  1925. .. math ::
  1926. \sigma_k^*(n) = \prod_{i=1}^\omega (1+ p_i^{m_ik}).
  1927. Parameters
  1928. ==========
  1929. k : power of divisors in the sum
  1930. for k = 0, 1:
  1931. ``udivisor_sigma(n, 0)`` is equal to ``udivisor_count(n)``
  1932. ``udivisor_sigma(n, 1)`` is equal to ``sum(udivisors(n))``
  1933. Default for k is 1.
  1934. Examples
  1935. ========
  1936. >>> from sympy.functions.combinatorial.numbers import udivisor_sigma
  1937. >>> udivisor_sigma(18, 0)
  1938. 4
  1939. >>> udivisor_sigma(74, 1)
  1940. 114
  1941. >>> udivisor_sigma(36, 3)
  1942. 47450
  1943. >>> udivisor_sigma(111)
  1944. 152
  1945. See Also
  1946. ========
  1947. divisor_count, totient, divisors, udivisors, udivisor_count, divisor_sigma,
  1948. factorint
  1949. References
  1950. ==========
  1951. .. [1] https://mathworld.wolfram.com/UnitaryDivisorFunction.html
  1952. """
  1953. from sympy.functions.combinatorial.numbers import udivisor_sigma as _udivisor_sigma
  1954. return _udivisor_sigma(n, k)
  1955. @deprecated("""\
  1956. The `sympy.ntheory.factor_.primenu` has been moved to `sympy.functions.combinatorial.numbers.primenu`.""",
  1957. deprecated_since_version="1.13",
  1958. active_deprecations_target='deprecated-ntheory-symbolic-functions')
  1959. def primenu(n):
  1960. r"""
  1961. Calculate the number of distinct prime factors for a positive integer n.
  1962. .. deprecated:: 1.13
  1963. The ``primenu`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.primenu`
  1964. instead. See its documentation for more information. See
  1965. :ref:`deprecated-ntheory-symbolic-functions` for details.
  1966. If n's prime factorization is:
  1967. .. math ::
  1968. n = \prod_{i=1}^k p_i^{m_i},
  1969. then ``primenu(n)`` or `\nu(n)` is:
  1970. .. math ::
  1971. \nu(n) = k.
  1972. Examples
  1973. ========
  1974. >>> from sympy.functions.combinatorial.numbers import primenu
  1975. >>> primenu(1)
  1976. 0
  1977. >>> primenu(30)
  1978. 3
  1979. See Also
  1980. ========
  1981. factorint
  1982. References
  1983. ==========
  1984. .. [1] https://mathworld.wolfram.com/PrimeFactor.html
  1985. """
  1986. from sympy.functions.combinatorial.numbers import primenu as _primenu
  1987. return _primenu(n)
  1988. @deprecated("""\
  1989. The `sympy.ntheory.factor_.primeomega` has been moved to `sympy.functions.combinatorial.numbers.primeomega`.""",
  1990. deprecated_since_version="1.13",
  1991. active_deprecations_target='deprecated-ntheory-symbolic-functions')
  1992. def primeomega(n):
  1993. r"""
  1994. Calculate the number of prime factors counting multiplicities for a
  1995. positive integer n.
  1996. .. deprecated:: 1.13
  1997. The ``primeomega`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.primeomega`
  1998. instead. See its documentation for more information. See
  1999. :ref:`deprecated-ntheory-symbolic-functions` for details.
  2000. If n's prime factorization is:
  2001. .. math ::
  2002. n = \prod_{i=1}^k p_i^{m_i},
  2003. then ``primeomega(n)`` or `\Omega(n)` is:
  2004. .. math ::
  2005. \Omega(n) = \sum_{i=1}^k m_i.
  2006. Examples
  2007. ========
  2008. >>> from sympy.functions.combinatorial.numbers import primeomega
  2009. >>> primeomega(1)
  2010. 0
  2011. >>> primeomega(20)
  2012. 3
  2013. See Also
  2014. ========
  2015. factorint
  2016. References
  2017. ==========
  2018. .. [1] https://mathworld.wolfram.com/PrimeFactor.html
  2019. """
  2020. from sympy.functions.combinatorial.numbers import primeomega as _primeomega
  2021. return _primeomega(n)
  2022. def mersenne_prime_exponent(nth):
  2023. """Returns the exponent ``i`` for the nth Mersenne prime (which
  2024. has the form `2^i - 1`).
  2025. Examples
  2026. ========
  2027. >>> from sympy.ntheory.factor_ import mersenne_prime_exponent
  2028. >>> mersenne_prime_exponent(1)
  2029. 2
  2030. >>> mersenne_prime_exponent(20)
  2031. 4423
  2032. """
  2033. n = as_int(nth)
  2034. if n < 1:
  2035. raise ValueError("nth must be a positive integer; mersenne_prime_exponent(1) == 2")
  2036. if n > 51:
  2037. raise ValueError("There are only 51 perfect numbers; nth must be less than or equal to 51")
  2038. return MERSENNE_PRIME_EXPONENTS[n - 1]
  2039. def is_perfect(n):
  2040. """Returns True if ``n`` is a perfect number, else False.
  2041. A perfect number is equal to the sum of its positive, proper divisors.
  2042. Examples
  2043. ========
  2044. >>> from sympy.functions.combinatorial.numbers import divisor_sigma
  2045. >>> from sympy.ntheory.factor_ import is_perfect, divisors
  2046. >>> is_perfect(20)
  2047. False
  2048. >>> is_perfect(6)
  2049. True
  2050. >>> 6 == divisor_sigma(6) - 6 == sum(divisors(6)[:-1])
  2051. True
  2052. References
  2053. ==========
  2054. .. [1] https://mathworld.wolfram.com/PerfectNumber.html
  2055. .. [2] https://en.wikipedia.org/wiki/Perfect_number
  2056. """
  2057. n = as_int(n)
  2058. if n < 1:
  2059. return False
  2060. if n % 2 == 0:
  2061. m = (n.bit_length() + 1) >> 1
  2062. if (1 << (m - 1)) * ((1 << m) - 1) != n:
  2063. # Even perfect numbers must be of the form `2^{m-1}(2^m-1)`
  2064. return False
  2065. return m in MERSENNE_PRIME_EXPONENTS or is_mersenne_prime(2**m - 1)
  2066. # n is an odd integer
  2067. if n < 10**2000: # https://www.lirmm.fr/~ochem/opn/
  2068. return False
  2069. if n % 105 == 0: # not divis by 105
  2070. return False
  2071. if all(n % m != r for m, r in [(12, 1), (468, 117), (324, 81)]):
  2072. return False
  2073. # there are many criteria that the factor structure of n
  2074. # must meet; since we will have to factor it to test the
  2075. # structure we will have the factors and can then check
  2076. # to see whether it is a perfect number or not. So we
  2077. # skip the structure checks and go straight to the final
  2078. # test below.
  2079. result = abundance(n) == 0
  2080. if result:
  2081. raise ValueError(filldedent('''In 1888, Sylvester stated: "
  2082. ...a prolonged meditation on the subject has satisfied
  2083. me that the existence of any one such [odd perfect number]
  2084. -- its escape, so to say, from the complex web of conditions
  2085. which hem it in on all sides -- would be little short of a
  2086. miracle." I guess SymPy just found that miracle and it
  2087. factors like this: %s''' % factorint(n)))
  2088. return result
  2089. def abundance(n):
  2090. """Returns the difference between the sum of the positive
  2091. proper divisors of a number and the number.
  2092. Examples
  2093. ========
  2094. >>> from sympy.ntheory import abundance, is_perfect, is_abundant
  2095. >>> abundance(6)
  2096. 0
  2097. >>> is_perfect(6)
  2098. True
  2099. >>> abundance(10)
  2100. -2
  2101. >>> is_abundant(10)
  2102. False
  2103. """
  2104. return _divisor_sigma(n) - 2 * n
  2105. def is_abundant(n):
  2106. """Returns True if ``n`` is an abundant number, else False.
  2107. A abundant number is smaller than the sum of its positive proper divisors.
  2108. Examples
  2109. ========
  2110. >>> from sympy.ntheory.factor_ import is_abundant
  2111. >>> is_abundant(20)
  2112. True
  2113. >>> is_abundant(15)
  2114. False
  2115. References
  2116. ==========
  2117. .. [1] https://mathworld.wolfram.com/AbundantNumber.html
  2118. """
  2119. n = as_int(n)
  2120. if is_perfect(n):
  2121. return False
  2122. return n % 6 == 0 or bool(abundance(n) > 0)
  2123. def is_deficient(n):
  2124. """Returns True if ``n`` is a deficient number, else False.
  2125. A deficient number is greater than the sum of its positive proper divisors.
  2126. Examples
  2127. ========
  2128. >>> from sympy.ntheory.factor_ import is_deficient
  2129. >>> is_deficient(20)
  2130. False
  2131. >>> is_deficient(15)
  2132. True
  2133. References
  2134. ==========
  2135. .. [1] https://mathworld.wolfram.com/DeficientNumber.html
  2136. """
  2137. n = as_int(n)
  2138. if is_perfect(n):
  2139. return False
  2140. return bool(abundance(n) < 0)
  2141. def is_amicable(m, n):
  2142. """Returns True if the numbers `m` and `n` are "amicable", else False.
  2143. Amicable numbers are two different numbers so related that the sum
  2144. of the proper divisors of each is equal to that of the other.
  2145. Examples
  2146. ========
  2147. >>> from sympy.functions.combinatorial.numbers import divisor_sigma
  2148. >>> from sympy.ntheory.factor_ import is_amicable
  2149. >>> is_amicable(220, 284)
  2150. True
  2151. >>> divisor_sigma(220) == divisor_sigma(284)
  2152. True
  2153. References
  2154. ==========
  2155. .. [1] https://en.wikipedia.org/wiki/Amicable_numbers
  2156. """
  2157. return m != n and m + n == _divisor_sigma(m) == _divisor_sigma(n)
  2158. def is_carmichael(n):
  2159. """ Returns True if the numbers `n` is Carmichael number, else False.
  2160. Parameters
  2161. ==========
  2162. n : Integer
  2163. References
  2164. ==========
  2165. .. [1] https://en.wikipedia.org/wiki/Carmichael_number
  2166. .. [2] https://oeis.org/A002997
  2167. """
  2168. if n < 561:
  2169. return False
  2170. return n % 2 and not isprime(n) and \
  2171. all(e == 1 and (n - 1) % (p - 1) == 0 for p, e in factorint(n).items())
  2172. def find_carmichael_numbers_in_range(x, y):
  2173. """ Returns a list of the number of Carmichael in the range
  2174. See Also
  2175. ========
  2176. is_carmichael
  2177. """
  2178. if 0 <= x <= y:
  2179. if x % 2 == 0:
  2180. return [i for i in range(x + 1, y, 2) if is_carmichael(i)]
  2181. else:
  2182. return [i for i in range(x, y, 2) if is_carmichael(i)]
  2183. else:
  2184. raise ValueError('The provided range is not valid. x and y must be non-negative integers and x <= y')
  2185. def find_first_n_carmichaels(n):
  2186. """ Returns the first n Carmichael numbers.
  2187. Parameters
  2188. ==========
  2189. n : Integer
  2190. See Also
  2191. ========
  2192. is_carmichael
  2193. """
  2194. i = 561
  2195. carmichaels = []
  2196. while len(carmichaels) < n:
  2197. if is_carmichael(i):
  2198. carmichaels.append(i)
  2199. i += 2
  2200. return carmichaels
  2201. def dra(n, b):
  2202. """
  2203. Returns the additive digital root of a natural number ``n`` in base ``b``
  2204. which is a single digit value obtained by an iterative process of summing
  2205. digits, on each iteration using the result from the previous iteration to
  2206. compute a digit sum.
  2207. Examples
  2208. ========
  2209. >>> from sympy.ntheory.factor_ import dra
  2210. >>> dra(3110, 12)
  2211. 8
  2212. References
  2213. ==========
  2214. .. [1] https://en.wikipedia.org/wiki/Digital_root
  2215. """
  2216. num = abs(as_int(n))
  2217. b = as_int(b)
  2218. if b <= 1:
  2219. raise ValueError("Base should be an integer greater than 1")
  2220. if num == 0:
  2221. return 0
  2222. return (1 + (num - 1) % (b - 1))
  2223. def drm(n, b):
  2224. """
  2225. Returns the multiplicative digital root of a natural number ``n`` in a given
  2226. base ``b`` which is a single digit value obtained by an iterative process of
  2227. multiplying digits, on each iteration using the result from the previous
  2228. iteration to compute the digit multiplication.
  2229. Examples
  2230. ========
  2231. >>> from sympy.ntheory.factor_ import drm
  2232. >>> drm(9876, 10)
  2233. 0
  2234. >>> drm(49, 10)
  2235. 8
  2236. References
  2237. ==========
  2238. .. [1] https://mathworld.wolfram.com/MultiplicativeDigitalRoot.html
  2239. """
  2240. n = abs(as_int(n))
  2241. b = as_int(b)
  2242. if b <= 1:
  2243. raise ValueError("Base should be an integer greater than 1")
  2244. while n > b:
  2245. mul = 1
  2246. while n > 1:
  2247. n, r = divmod(n, b)
  2248. if r == 0:
  2249. return 0
  2250. mul *= r
  2251. n = mul
  2252. return n