factor_.py 74 KB

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