generate.py 30 KB

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