generate.py 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157
  1. """
  2. Generating and counting primes.
  3. """
  4. from bisect import bisect, bisect_left
  5. from itertools import count
  6. # Using arrays for sieving instead of lists greatly reduces
  7. # memory consumption
  8. from array import array as _array
  9. from sympy.core.random import randint
  10. from sympy.external.gmpy import sqrt
  11. from .primetest import isprime
  12. from sympy.utilities.decorator import deprecated
  13. from sympy.utilities.misc import as_int
  14. def _as_int_ceiling(a):
  15. """ Wrapping ceiling in as_int will raise an error if there was a problem
  16. determining whether the expression was exactly an integer or not."""
  17. from sympy.functions.elementary.integers import ceiling
  18. return as_int(ceiling(a))
  19. class Sieve:
  20. """A list of prime numbers, implemented as a dynamically
  21. growing sieve of Eratosthenes. When a lookup is requested involving
  22. an odd number that has not been sieved, the sieve is automatically
  23. extended up to that number. Implementation details limit the number of
  24. primes to ``2^32-1``.
  25. Examples
  26. ========
  27. >>> from sympy import sieve
  28. >>> sieve._reset() # this line for doctest only
  29. >>> 25 in sieve
  30. False
  31. >>> sieve._list
  32. array('L', [2, 3, 5, 7, 11, 13, 17, 19, 23])
  33. """
  34. # data shared (and updated) by all Sieve instances
  35. def __init__(self, sieve_interval=1_000_000):
  36. """ Initial parameters for the Sieve class.
  37. Parameters
  38. ==========
  39. sieve_interval (int): Amount of memory to be used
  40. Raises
  41. ======
  42. ValueError
  43. If ``sieve_interval`` is not positive.
  44. """
  45. self._n = 6
  46. self._list = _array('L', [2, 3, 5, 7, 11, 13]) # primes
  47. self._tlist = _array('L', [0, 1, 1, 2, 2, 4]) # totient
  48. self._mlist = _array('i', [0, 1, -1, -1, 0, -1]) # mobius
  49. if sieve_interval <= 0:
  50. raise ValueError("sieve_interval should be a positive integer")
  51. self.sieve_interval = sieve_interval
  52. assert all(len(i) == self._n for i in (self._list, self._tlist, self._mlist))
  53. def __repr__(self):
  54. return ("<%s sieve (%i): %i, %i, %i, ... %i, %i\n"
  55. "%s sieve (%i): %i, %i, %i, ... %i, %i\n"
  56. "%s sieve (%i): %i, %i, %i, ... %i, %i>") % (
  57. 'prime', len(self._list),
  58. self._list[0], self._list[1], self._list[2],
  59. self._list[-2], self._list[-1],
  60. 'totient', len(self._tlist),
  61. self._tlist[0], self._tlist[1],
  62. self._tlist[2], self._tlist[-2], self._tlist[-1],
  63. 'mobius', len(self._mlist),
  64. self._mlist[0], self._mlist[1],
  65. self._mlist[2], self._mlist[-2], self._mlist[-1])
  66. def _reset(self, prime=None, totient=None, mobius=None):
  67. """Reset all caches (default). To reset one or more set the
  68. desired keyword to True."""
  69. if all(i is None for i in (prime, totient, mobius)):
  70. prime = totient = mobius = True
  71. if prime:
  72. self._list = self._list[:self._n]
  73. if totient:
  74. self._tlist = self._tlist[:self._n]
  75. if mobius:
  76. self._mlist = self._mlist[:self._n]
  77. def extend(self, n):
  78. """Grow the sieve to cover all primes <= n.
  79. Examples
  80. ========
  81. >>> from sympy import sieve
  82. >>> sieve._reset() # this line for doctest only
  83. >>> sieve.extend(30)
  84. >>> sieve[10] == 29
  85. True
  86. """
  87. n = int(n)
  88. # `num` is even at any point in the function.
  89. # This satisfies the condition required by `self._primerange`.
  90. num = self._list[-1] + 1
  91. if n < num:
  92. return
  93. num2 = num**2
  94. while num2 <= n:
  95. self._list += _array('L', self._primerange(num, num2))
  96. num, num2 = num2, num2**2
  97. # Merge the sieves
  98. self._list += _array('L', self._primerange(num, n + 1))
  99. def _primerange(self, a, b):
  100. """ Generate all prime numbers in the range (a, b).
  101. Parameters
  102. ==========
  103. a, b : positive integers assuming the following conditions
  104. * a is an even number
  105. * 2 < self._list[-1] < a < b < nextprime(self._list[-1])**2
  106. Yields
  107. ======
  108. p (int): prime numbers such that ``a < p < b``
  109. Examples
  110. ========
  111. >>> from sympy.ntheory.generate import Sieve
  112. >>> s = Sieve()
  113. >>> s._list[-1]
  114. 13
  115. >>> list(s._primerange(18, 31))
  116. [19, 23, 29]
  117. """
  118. if b % 2:
  119. b -= 1
  120. while a < b:
  121. block_size = min(self.sieve_interval, (b - a) // 2)
  122. # Create the list such that block[x] iff (a + 2x + 1) is prime.
  123. # Note that even numbers are not considered here.
  124. block = [True] * block_size
  125. for p in self._list[1:bisect(self._list, sqrt(a + 2 * block_size + 1))]:
  126. for t in range((-(a + 1 + p) // 2) % p, block_size, p):
  127. block[t] = False
  128. for idx, p in enumerate(block):
  129. if p:
  130. yield a + 2 * idx + 1
  131. a += 2 * block_size
  132. def extend_to_no(self, i):
  133. """Extend to include the ith prime number.
  134. Parameters
  135. ==========
  136. i : integer
  137. Examples
  138. ========
  139. >>> from sympy import sieve
  140. >>> sieve._reset() # this line for doctest only
  141. >>> sieve.extend_to_no(9)
  142. >>> sieve._list
  143. array('L', [2, 3, 5, 7, 11, 13, 17, 19, 23])
  144. Notes
  145. =====
  146. The list is extended by 50% if it is too short, so it is
  147. likely that it will be longer than requested.
  148. """
  149. i = as_int(i)
  150. while len(self._list) < i:
  151. self.extend(int(self._list[-1] * 1.5))
  152. def primerange(self, a, b=None):
  153. """Generate all prime numbers in the range [2, a) or [a, b).
  154. Examples
  155. ========
  156. >>> from sympy import sieve, prime
  157. All primes less than 19:
  158. >>> print([i for i in sieve.primerange(19)])
  159. [2, 3, 5, 7, 11, 13, 17]
  160. All primes greater than or equal to 7 and less than 19:
  161. >>> print([i for i in sieve.primerange(7, 19)])
  162. [7, 11, 13, 17]
  163. All primes through the 10th prime
  164. >>> list(sieve.primerange(prime(10) + 1))
  165. [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
  166. """
  167. if b is None:
  168. b = _as_int_ceiling(a)
  169. a = 2
  170. else:
  171. a = max(2, _as_int_ceiling(a))
  172. b = _as_int_ceiling(b)
  173. if a >= b:
  174. return
  175. self.extend(b)
  176. yield from self._list[bisect_left(self._list, a):
  177. bisect_left(self._list, b)]
  178. def totientrange(self, a, b):
  179. """Generate all totient numbers for the range [a, b).
  180. Examples
  181. ========
  182. >>> from sympy import sieve
  183. >>> print([i for i in sieve.totientrange(7, 18)])
  184. [6, 4, 6, 4, 10, 4, 12, 6, 8, 8, 16]
  185. """
  186. a = max(1, _as_int_ceiling(a))
  187. b = _as_int_ceiling(b)
  188. n = len(self._tlist)
  189. if a >= b:
  190. return
  191. elif b <= n:
  192. for i in range(a, b):
  193. yield self._tlist[i]
  194. else:
  195. self._tlist += _array('L', range(n, b))
  196. for i in range(1, n):
  197. ti = self._tlist[i]
  198. if ti == i - 1:
  199. startindex = (n + i - 1) // i * i
  200. for j in range(startindex, b, i):
  201. self._tlist[j] -= self._tlist[j] // i
  202. if i >= a:
  203. yield ti
  204. for i in range(n, b):
  205. ti = self._tlist[i]
  206. if ti == i:
  207. for j in range(i, b, i):
  208. self._tlist[j] -= self._tlist[j] // i
  209. if i >= a:
  210. yield self._tlist[i]
  211. def mobiusrange(self, a, b):
  212. """Generate all mobius numbers for the range [a, b).
  213. Parameters
  214. ==========
  215. a : integer
  216. First number in range
  217. b : integer
  218. First number outside of range
  219. Examples
  220. ========
  221. >>> from sympy import sieve
  222. >>> print([i for i in sieve.mobiusrange(7, 18)])
  223. [-1, 0, 0, 1, -1, 0, -1, 1, 1, 0, -1]
  224. """
  225. a = max(1, _as_int_ceiling(a))
  226. b = _as_int_ceiling(b)
  227. n = len(self._mlist)
  228. if a >= b:
  229. return
  230. elif b <= n:
  231. for i in range(a, b):
  232. yield self._mlist[i]
  233. else:
  234. self._mlist += _array('i', [0]*(b - n))
  235. for i in range(1, n):
  236. mi = self._mlist[i]
  237. startindex = (n + i - 1) // i * i
  238. for j in range(startindex, b, i):
  239. self._mlist[j] -= mi
  240. if i >= a:
  241. yield mi
  242. for i in range(n, b):
  243. mi = self._mlist[i]
  244. for j in range(2 * i, b, i):
  245. self._mlist[j] -= mi
  246. if i >= a:
  247. yield mi
  248. def search(self, n):
  249. """Return the indices i, j of the primes that bound n.
  250. If n is prime then i == j.
  251. Although n can be an expression, if ceiling cannot convert
  252. it to an integer then an n error will be raised.
  253. Examples
  254. ========
  255. >>> from sympy import sieve
  256. >>> sieve.search(25)
  257. (9, 10)
  258. >>> sieve.search(23)
  259. (9, 9)
  260. """
  261. test = _as_int_ceiling(n)
  262. n = as_int(n)
  263. if n < 2:
  264. raise ValueError("n should be >= 2 but got: %s" % n)
  265. if n > self._list[-1]:
  266. self.extend(n)
  267. b = bisect(self._list, n)
  268. if self._list[b - 1] == test:
  269. return b, b
  270. else:
  271. return b, b + 1
  272. def __contains__(self, n):
  273. try:
  274. n = as_int(n)
  275. assert n >= 2
  276. except (ValueError, AssertionError):
  277. return False
  278. if n % 2 == 0:
  279. return n == 2
  280. a, b = self.search(n)
  281. return a == b
  282. def __iter__(self):
  283. for n in count(1):
  284. yield self[n]
  285. def __getitem__(self, n):
  286. """Return the nth prime number"""
  287. if isinstance(n, slice):
  288. self.extend_to_no(n.stop)
  289. start = n.start if n.start is not None else 0
  290. if start < 1:
  291. # sieve[:5] would be empty (starting at -1), let's
  292. # just be explicit and raise.
  293. raise IndexError("Sieve indices start at 1.")
  294. return self._list[start - 1:n.stop - 1:n.step]
  295. else:
  296. if n < 1:
  297. # offset is one, so forbid explicit access to sieve[0]
  298. # (would surprisingly return the last one).
  299. raise IndexError("Sieve indices start at 1.")
  300. n = as_int(n)
  301. self.extend_to_no(n)
  302. return self._list[n - 1]
  303. # Generate a global object for repeated use in trial division etc
  304. sieve = Sieve()
  305. def prime(nth):
  306. r"""
  307. Return the nth prime number, where primes are indexed starting from 1:
  308. prime(1) = 2, prime(2) = 3, etc.
  309. Parameters
  310. ==========
  311. nth : int
  312. The position of the prime number to return (must be a positive integer).
  313. Returns
  314. =======
  315. int
  316. The nth prime number.
  317. Examples
  318. ========
  319. >>> from sympy import prime
  320. >>> prime(10)
  321. 29
  322. >>> prime(1)
  323. 2
  324. >>> prime(100000)
  325. 1299709
  326. See Also
  327. ========
  328. sympy.ntheory.primetest.isprime : Test if a number is prime.
  329. primerange : Generate all primes in a given range.
  330. primepi : Return the number of primes less than or equal to a given number.
  331. References
  332. ==========
  333. .. [1] https://en.wikipedia.org/wiki/Prime_number_theorem
  334. .. [2] https://en.wikipedia.org/wiki/Logarithmic_integral_function
  335. .. [3] https://en.wikipedia.org/wiki/Skewes%27_number
  336. """
  337. n = as_int(nth)
  338. if n < 1:
  339. raise ValueError("nth must be a positive integer; prime(1) == 2")
  340. # Check if n is within the sieve range
  341. if n <= len(sieve._list):
  342. return sieve[n]
  343. from sympy.functions.elementary.exponential import log
  344. from sympy.functions.special.error_functions import li
  345. if n < 1000:
  346. # Extend sieve up to 8*n as this is empirically sufficient
  347. sieve.extend(8 * n)
  348. return sieve[n]
  349. a = 2
  350. # Estimate an upper bound for the nth prime using the prime number theorem
  351. b = int(n * (log(n).evalf() + log(log(n)).evalf()))
  352. # Binary search for the least m such that li(m) > n
  353. while a < b:
  354. mid = (a + b) >> 1
  355. if li(mid).evalf() > n:
  356. b = mid
  357. else:
  358. a = mid + 1
  359. return nextprime(a - 1, n - _primepi(a - 1))
  360. @deprecated("""\
  361. The `sympy.ntheory.generate.primepi` has been moved to `sympy.functions.combinatorial.numbers.primepi`.""",
  362. deprecated_since_version="1.13",
  363. active_deprecations_target='deprecated-ntheory-symbolic-functions')
  364. def primepi(n):
  365. r""" Represents the prime counting function pi(n) = the number
  366. of prime numbers less than or equal to n.
  367. .. deprecated:: 1.13
  368. The ``primepi`` function is deprecated. Use :class:`sympy.functions.combinatorial.numbers.primepi`
  369. instead. See its documentation for more information. See
  370. :ref:`deprecated-ntheory-symbolic-functions` for details.
  371. Algorithm Description:
  372. In sieve method, we remove all multiples of prime p
  373. except p itself.
  374. Let phi(i,j) be the number of integers 2 <= k <= i
  375. which remain after sieving from primes less than
  376. or equal to j.
  377. Clearly, pi(n) = phi(n, sqrt(n))
  378. If j is not a prime,
  379. phi(i,j) = phi(i, j - 1)
  380. if j is a prime,
  381. We remove all numbers(except j) whose
  382. smallest prime factor is j.
  383. Let $x= j \times a$ be such a number, where $2 \le a \le i / j$
  384. Now, after sieving from primes $\le j - 1$,
  385. a must remain
  386. (because x, and hence a has no prime factor $\le j - 1$)
  387. Clearly, there are phi(i / j, j - 1) such a
  388. which remain on sieving from primes $\le j - 1$
  389. Now, if a is a prime less than equal to j - 1,
  390. $x= j \times a$ has smallest prime factor = a, and
  391. has already been removed(by sieving from a).
  392. So, we do not need to remove it again.
  393. (Note: there will be pi(j - 1) such x)
  394. Thus, number of x, that will be removed are:
  395. phi(i / j, j - 1) - phi(j - 1, j - 1)
  396. (Note that pi(j - 1) = phi(j - 1, j - 1))
  397. $\Rightarrow$ phi(i,j) = phi(i, j - 1) - phi(i / j, j - 1) + phi(j - 1, j - 1)
  398. So,following recursion is used and implemented as dp:
  399. phi(a, b) = phi(a, b - 1), if b is not a prime
  400. phi(a, b) = phi(a, b-1)-phi(a / b, b-1) + phi(b-1, b-1), if b is prime
  401. Clearly a is always of the form floor(n / k),
  402. which can take at most $2\sqrt{n}$ values.
  403. Two arrays arr1,arr2 are maintained
  404. arr1[i] = phi(i, j),
  405. arr2[i] = phi(n // i, j)
  406. Finally the answer is arr2[1]
  407. Examples
  408. ========
  409. >>> from sympy import primepi, prime, prevprime, isprime
  410. >>> primepi(25)
  411. 9
  412. So there are 9 primes less than or equal to 25. Is 25 prime?
  413. >>> isprime(25)
  414. False
  415. It is not. So the first prime less than 25 must be the
  416. 9th prime:
  417. >>> prevprime(25) == prime(9)
  418. True
  419. See Also
  420. ========
  421. sympy.ntheory.primetest.isprime : Test if n is prime
  422. primerange : Generate all primes in a given range
  423. prime : Return the nth prime
  424. """
  425. from sympy.functions.combinatorial.numbers import primepi as func_primepi
  426. return func_primepi(n)
  427. def _primepi(n:int) -> int:
  428. r""" Represents the prime counting function pi(n) = the number
  429. of prime numbers less than or equal to n.
  430. Explanation
  431. ===========
  432. In sieve method, we remove all multiples of prime p
  433. except p itself.
  434. Let phi(i,j) be the number of integers 2 <= k <= i
  435. which remain after sieving from primes less than
  436. or equal to j.
  437. Clearly, pi(n) = phi(n, sqrt(n))
  438. If j is not a prime,
  439. phi(i,j) = phi(i, j - 1)
  440. if j is a prime,
  441. We remove all numbers(except j) whose
  442. smallest prime factor is j.
  443. Let $x= j \times a$ be such a number, where $2 \le a \le i / j$
  444. Now, after sieving from primes $\le j - 1$,
  445. a must remain
  446. (because x, and hence a has no prime factor $\le j - 1$)
  447. Clearly, there are phi(i / j, j - 1) such a
  448. which remain on sieving from primes $\le j - 1$
  449. Now, if a is a prime less than equal to j - 1,
  450. $x= j \times a$ has smallest prime factor = a, and
  451. has already been removed(by sieving from a).
  452. So, we do not need to remove it again.
  453. (Note: there will be pi(j - 1) such x)
  454. Thus, number of x, that will be removed are:
  455. phi(i / j, j - 1) - phi(j - 1, j - 1)
  456. (Note that pi(j - 1) = phi(j - 1, j - 1))
  457. $\Rightarrow$ phi(i,j) = phi(i, j - 1) - phi(i / j, j - 1) + phi(j - 1, j - 1)
  458. So,following recursion is used and implemented as dp:
  459. phi(a, b) = phi(a, b - 1), if b is not a prime
  460. phi(a, b) = phi(a, b-1)-phi(a / b, b-1) + phi(b-1, b-1), if b is prime
  461. Clearly a is always of the form floor(n / k),
  462. which can take at most $2\sqrt{n}$ values.
  463. Two arrays arr1,arr2 are maintained
  464. arr1[i] = phi(i, j),
  465. arr2[i] = phi(n // i, j)
  466. Finally the answer is arr2[1]
  467. Parameters
  468. ==========
  469. n : int
  470. """
  471. if n < 2:
  472. return 0
  473. if n <= sieve._list[-1]:
  474. return sieve.search(n)[0]
  475. lim = sqrt(n)
  476. arr1 = [(i + 1) >> 1 for i in range(lim + 1)]
  477. arr2 = [0] + [(n//i + 1) >> 1 for i in range(1, lim + 1)]
  478. skip = [False] * (lim + 1)
  479. for i in range(3, lim + 1, 2):
  480. # Presently, arr1[k]=phi(k,i - 1),
  481. # arr2[k] = phi(n // k,i - 1) # not all k's do this
  482. if skip[i]:
  483. # skip if i is a composite number
  484. continue
  485. p = arr1[i - 1]
  486. for j in range(i, lim + 1, i):
  487. skip[j] = True
  488. # update arr2
  489. # phi(n/j, i) = phi(n/j, i-1) - phi(n/(i*j), i-1) + phi(i-1, i-1)
  490. for j in range(1, min(n // (i * i), lim) + 1, 2):
  491. # No need for arr2[j] in j such that skip[j] is True to
  492. # compute the final required arr2[1].
  493. if skip[j]:
  494. continue
  495. st = i * j
  496. if st <= lim:
  497. arr2[j] -= arr2[st] - p
  498. else:
  499. arr2[j] -= arr1[n // st] - p
  500. # update arr1
  501. # phi(j, i) = phi(j, i-1) - phi(j/i, i-1) + phi(i-1, i-1)
  502. # where the range below i**2 is fixed and
  503. # does not need to be calculated.
  504. for j in range(lim, min(lim, i*i - 1), -1):
  505. arr1[j] -= arr1[j // i] - p
  506. return arr2[1]
  507. def nextprime(n, ith=1):
  508. """ Return the ith prime greater than n.
  509. Parameters
  510. ==========
  511. n : integer
  512. ith : positive integer
  513. Returns
  514. =======
  515. int : Return the ith prime greater than n
  516. Raises
  517. ======
  518. ValueError
  519. If ``ith <= 0``.
  520. If ``n`` or ``ith`` is not an integer.
  521. Notes
  522. =====
  523. Potential primes are located at 6*j +/- 1. This
  524. property is used during searching.
  525. >>> from sympy import nextprime
  526. >>> [(i, nextprime(i)) for i in range(10, 15)]
  527. [(10, 11), (11, 13), (12, 13), (13, 17), (14, 17)]
  528. >>> nextprime(2, ith=2) # the 2nd prime after 2
  529. 5
  530. See Also
  531. ========
  532. prevprime : Return the largest prime smaller than n
  533. primerange : Generate all primes in a given range
  534. """
  535. n = int(n)
  536. i = as_int(ith)
  537. if i <= 0:
  538. raise ValueError("ith should be positive")
  539. if n < 2:
  540. n = 2
  541. i -= 1
  542. if n <= sieve._list[-2]:
  543. l, _ = sieve.search(n)
  544. if l + i - 1 < len(sieve._list):
  545. return sieve._list[l + i - 1]
  546. n = sieve._list[-1]
  547. i += l - len(sieve._list)
  548. nn = 6*(n//6)
  549. if nn == n:
  550. n += 1
  551. if isprime(n):
  552. i -= 1
  553. if not i:
  554. return n
  555. n += 4
  556. elif n - nn == 5:
  557. n += 2
  558. if isprime(n):
  559. i -= 1
  560. if not i:
  561. return n
  562. n += 4
  563. else:
  564. n = nn + 5
  565. while 1:
  566. if isprime(n):
  567. i -= 1
  568. if not i:
  569. return n
  570. n += 2
  571. if isprime(n):
  572. i -= 1
  573. if not i:
  574. return n
  575. n += 4
  576. def prevprime(n):
  577. """ Return the largest prime smaller than n.
  578. Notes
  579. =====
  580. Potential primes are located at 6*j +/- 1. This
  581. property is used during searching.
  582. >>> from sympy import prevprime
  583. >>> [(i, prevprime(i)) for i in range(10, 15)]
  584. [(10, 7), (11, 7), (12, 11), (13, 11), (14, 13)]
  585. See Also
  586. ========
  587. nextprime : Return the ith prime greater than n
  588. primerange : Generates all primes in a given range
  589. """
  590. n = _as_int_ceiling(n)
  591. if n < 3:
  592. raise ValueError("no preceding primes")
  593. if n < 8:
  594. return {3: 2, 4: 3, 5: 3, 6: 5, 7: 5}[n]
  595. if n <= sieve._list[-1]:
  596. l, u = sieve.search(n)
  597. if l == u:
  598. return sieve[l-1]
  599. else:
  600. return sieve[l]
  601. nn = 6*(n//6)
  602. if n - nn <= 1:
  603. n = nn - 1
  604. if isprime(n):
  605. return n
  606. n -= 4
  607. else:
  608. n = nn + 1
  609. while 1:
  610. if isprime(n):
  611. return n
  612. n -= 2
  613. if isprime(n):
  614. return n
  615. n -= 4
  616. def primerange(a, b=None):
  617. """ Generate a list of all prime numbers in the range [2, a),
  618. or [a, b).
  619. If the range exists in the default sieve, the values will
  620. be returned from there; otherwise values will be returned
  621. but will not modify the sieve.
  622. Examples
  623. ========
  624. >>> from sympy import primerange, prime
  625. All primes less than 19:
  626. >>> list(primerange(19))
  627. [2, 3, 5, 7, 11, 13, 17]
  628. All primes greater than or equal to 7 and less than 19:
  629. >>> list(primerange(7, 19))
  630. [7, 11, 13, 17]
  631. All primes through the 10th prime
  632. >>> list(primerange(prime(10) + 1))
  633. [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
  634. The Sieve method, primerange, is generally faster but it will
  635. occupy more memory as the sieve stores values. The default
  636. instance of Sieve, named sieve, can be used:
  637. >>> from sympy import sieve
  638. >>> list(sieve.primerange(1, 30))
  639. [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
  640. Notes
  641. =====
  642. Some famous conjectures about the occurrence of primes in a given
  643. range are [1]:
  644. - Twin primes: though often not, the following will give 2 primes
  645. an infinite number of times:
  646. primerange(6*n - 1, 6*n + 2)
  647. - Legendre's: the following always yields at least one prime
  648. primerange(n**2, (n+1)**2+1)
  649. - Bertrand's (proven): there is always a prime in the range
  650. primerange(n, 2*n)
  651. - Brocard's: there are at least four primes in the range
  652. primerange(prime(n)**2, prime(n+1)**2)
  653. The average gap between primes is log(n) [2]; the gap between
  654. primes can be arbitrarily large since sequences of composite
  655. numbers are arbitrarily large, e.g. the numbers in the sequence
  656. n! + 2, n! + 3 ... n! + n are all composite.
  657. See Also
  658. ========
  659. prime : Return the nth prime
  660. nextprime : Return the ith prime greater than n
  661. prevprime : Return the largest prime smaller than n
  662. randprime : Returns a random prime in a given range
  663. primorial : Returns the product of primes based on condition
  664. Sieve.primerange : return range from already computed primes
  665. or extend the sieve to contain the requested
  666. range.
  667. References
  668. ==========
  669. .. [1] https://en.wikipedia.org/wiki/Prime_number
  670. .. [2] https://primes.utm.edu/notes/gaps.html
  671. """
  672. if b is None:
  673. a, b = 2, a
  674. if a >= b:
  675. return
  676. # If we already have the range, return it.
  677. largest_known_prime = sieve._list[-1]
  678. if b <= largest_known_prime:
  679. yield from sieve.primerange(a, b)
  680. return
  681. # If we know some of it, return it.
  682. if a <= largest_known_prime:
  683. yield from sieve._list[bisect_left(sieve._list, a):]
  684. a = largest_known_prime + 1
  685. elif a % 2:
  686. a -= 1
  687. tail = min(b, (largest_known_prime)**2)
  688. if a < tail:
  689. yield from sieve._primerange(a, tail)
  690. a = tail
  691. if b <= a:
  692. return
  693. # otherwise compute, without storing, the desired range.
  694. while 1:
  695. a = nextprime(a)
  696. if a < b:
  697. yield a
  698. else:
  699. return
  700. def randprime(a, b):
  701. """ Return a random prime number in the range [a, b).
  702. Bertrand's postulate assures that
  703. randprime(a, 2*a) will always succeed for a > 1.
  704. Note that due to implementation difficulties,
  705. the prime numbers chosen are not uniformly random.
  706. For example, there are two primes in the range [112, 128),
  707. ``113`` and ``127``, but ``randprime(112, 128)`` returns ``127``
  708. with a probability of 15/17.
  709. Examples
  710. ========
  711. >>> from sympy import randprime, isprime
  712. >>> randprime(1, 30) #doctest: +SKIP
  713. 13
  714. >>> isprime(randprime(1, 30))
  715. True
  716. See Also
  717. ========
  718. primerange : Generate all primes in a given range
  719. References
  720. ==========
  721. .. [1] https://en.wikipedia.org/wiki/Bertrand's_postulate
  722. """
  723. if a >= b:
  724. return
  725. a, b = map(int, (a, b))
  726. n = randint(a - 1, b)
  727. p = nextprime(n)
  728. if p >= b:
  729. p = prevprime(b)
  730. if p < a:
  731. raise ValueError("no primes exist in the specified range")
  732. return p
  733. def primorial(n, nth=True):
  734. """
  735. Returns the product of the first n primes (default) or
  736. the primes less than or equal to n (when ``nth=False``).
  737. Examples
  738. ========
  739. >>> from sympy.ntheory.generate import primorial, primerange
  740. >>> from sympy import factorint, Mul, primefactors, sqrt
  741. >>> primorial(4) # the first 4 primes are 2, 3, 5, 7
  742. 210
  743. >>> primorial(4, nth=False) # primes <= 4 are 2 and 3
  744. 6
  745. >>> primorial(1)
  746. 2
  747. >>> primorial(1, nth=False)
  748. 1
  749. >>> primorial(sqrt(101), nth=False)
  750. 210
  751. One can argue that the primes are infinite since if you take
  752. a set of primes and multiply them together (e.g. the primorial) and
  753. then add or subtract 1, the result cannot be divided by any of the
  754. original factors, hence either 1 or more new primes must divide this
  755. product of primes.
  756. In this case, the number itself is a new prime:
  757. >>> factorint(primorial(4) + 1)
  758. {211: 1}
  759. In this case two new primes are the factors:
  760. >>> factorint(primorial(4) - 1)
  761. {11: 1, 19: 1}
  762. Here, some primes smaller and larger than the primes multiplied together
  763. are obtained:
  764. >>> p = list(primerange(10, 20))
  765. >>> sorted(set(primefactors(Mul(*p) + 1)).difference(set(p)))
  766. [2, 5, 31, 149]
  767. See Also
  768. ========
  769. primerange : Generate all primes in a given range
  770. """
  771. if nth:
  772. n = as_int(n)
  773. else:
  774. n = int(n)
  775. if n < 1:
  776. raise ValueError("primorial argument must be >= 1")
  777. p = 1
  778. if nth:
  779. for i in range(1, n + 1):
  780. p *= prime(i)
  781. else:
  782. for i in primerange(2, n + 1):
  783. p *= i
  784. return p
  785. def cycle_length(f, x0, nmax=None, values=False):
  786. """For a given iterated sequence, return a generator that gives
  787. the length of the iterated cycle (lambda) and the length of terms
  788. before the cycle begins (mu); if ``values`` is True then the
  789. terms of the sequence will be returned instead. The sequence is
  790. started with value ``x0``.
  791. Note: more than the first lambda + mu terms may be returned and this
  792. is the cost of cycle detection with Brent's method; there are, however,
  793. generally less terms calculated than would have been calculated if the
  794. proper ending point were determined, e.g. by using Floyd's method.
  795. >>> from sympy.ntheory.generate import cycle_length
  796. This will yield successive values of i <-- func(i):
  797. >>> def gen(func, i):
  798. ... while 1:
  799. ... yield i
  800. ... i = func(i)
  801. ...
  802. A function is defined:
  803. >>> func = lambda i: (i**2 + 1) % 51
  804. and given a seed of 4 and the mu and lambda terms calculated:
  805. >>> next(cycle_length(func, 4))
  806. (6, 3)
  807. We can see what is meant by looking at the output:
  808. >>> iter = cycle_length(func, 4, values=True)
  809. >>> list(iter)
  810. [4, 17, 35, 2, 5, 26, 14, 44, 50, 2, 5, 26, 14]
  811. There are 6 repeating values after the first 3.
  812. If a sequence is suspected of being longer than you might wish, ``nmax``
  813. can be used to exit early (and mu will be returned as None):
  814. >>> next(cycle_length(func, 4, nmax = 4))
  815. (4, None)
  816. >>> list(cycle_length(func, 4, nmax = 4, values=True))
  817. [4, 17, 35, 2]
  818. Code modified from:
  819. https://en.wikipedia.org/wiki/Cycle_detection.
  820. """
  821. nmax = int(nmax or 0)
  822. # main phase: search successive powers of two
  823. power = lam = 1
  824. tortoise, hare = x0, f(x0) # f(x0) is the element/node next to x0.
  825. i = 1
  826. if values:
  827. yield tortoise
  828. while tortoise != hare and (not nmax or i < nmax):
  829. i += 1
  830. if power == lam: # time to start a new power of two?
  831. tortoise = hare
  832. power *= 2
  833. lam = 0
  834. if values:
  835. yield hare
  836. hare = f(hare)
  837. lam += 1
  838. if nmax and i == nmax:
  839. if values:
  840. return
  841. else:
  842. yield nmax, None
  843. return
  844. if not values:
  845. # Find the position of the first repetition of length lambda
  846. mu = 0
  847. tortoise = hare = x0
  848. for i in range(lam):
  849. hare = f(hare)
  850. while tortoise != hare:
  851. tortoise = f(tortoise)
  852. hare = f(hare)
  853. mu += 1
  854. yield lam, mu
  855. def composite(nth):
  856. """ Return the nth composite number, with the composite numbers indexed as
  857. composite(1) = 4, composite(2) = 6, etc....
  858. Examples
  859. ========
  860. >>> from sympy import composite
  861. >>> composite(36)
  862. 52
  863. >>> composite(1)
  864. 4
  865. >>> composite(17737)
  866. 20000
  867. See Also
  868. ========
  869. sympy.ntheory.primetest.isprime : Test if n is prime
  870. primerange : Generate all primes in a given range
  871. primepi : Return the number of primes less than or equal to n
  872. prime : Return the nth prime
  873. compositepi : Return the number of positive composite numbers less than or equal to n
  874. """
  875. n = as_int(nth)
  876. if n < 1:
  877. raise ValueError("nth must be a positive integer; composite(1) == 4")
  878. composite_arr = [4, 6, 8, 9, 10, 12, 14, 15, 16, 18]
  879. if n <= 10:
  880. return composite_arr[n - 1]
  881. a, b = 4, sieve._list[-1]
  882. if n <= b - _primepi(b) - 1:
  883. while a < b - 1:
  884. mid = (a + b) >> 1
  885. if mid - _primepi(mid) - 1 > n:
  886. b = mid
  887. else:
  888. a = mid
  889. if isprime(a):
  890. a -= 1
  891. return a
  892. from sympy.functions.elementary.exponential import log
  893. from sympy.functions.special.error_functions import li
  894. a = 4 # Lower bound for binary search
  895. b = int(n*(log(n) + log(log(n)))) # Upper bound for the search.
  896. while a < b:
  897. mid = (a + b) >> 1
  898. if mid - li(mid) - 1 > n:
  899. b = mid
  900. else:
  901. a = mid + 1
  902. n_composites = a - _primepi(a) - 1
  903. while n_composites > n:
  904. if not isprime(a):
  905. n_composites -= 1
  906. a -= 1
  907. if isprime(a):
  908. a -= 1
  909. return a
  910. def compositepi(n):
  911. """ Return the number of positive composite numbers less than or equal to n.
  912. The first positive composite is 4, i.e. compositepi(4) = 1.
  913. Examples
  914. ========
  915. >>> from sympy import compositepi
  916. >>> compositepi(25)
  917. 15
  918. >>> compositepi(1000)
  919. 831
  920. See Also
  921. ========
  922. sympy.ntheory.primetest.isprime : Test if n is prime
  923. primerange : Generate all primes in a given range
  924. prime : Return the nth prime
  925. primepi : Return the number of primes less than or equal to n
  926. composite : Return the nth composite number
  927. """
  928. n = int(n)
  929. if n < 4:
  930. return 0
  931. return n - _primepi(n) - 1