generate.py 29 KB

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