m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2661 lines
74 KiB

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