siqs_factorization.sf 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196
  1. #!/usr/bin/ruby
  2. # This script factorizes a natural number given as a command line
  3. # parameter into its prime factors. It first attempts to use trial
  4. # division to find very small factors, then uses Brent's version of the
  5. # Pollard rho algorithm [1] to find slightly larger factors. If any large
  6. # factors remain, it uses the Self-Initializing Quadratic Sieve (SIQS) [2]
  7. # to factorize those.
  8. # [1] Brent, Richard P. 'An improved Monte Carlo factorization algorithm.'
  9. # BIT Numerical Mathematics 20.2 (1980): 176-184.
  10. # [2] Contini, Scott Patrick. 'Factoring integers with the self-
  11. # initializing quadratic sieve.' (1997).
  12. STDOUT.autoflush(true)
  13. class SIQSPolynomial (coeff, a=nil, b=nil) {
  14. method eval (x) {
  15. var res = 0
  16. coeff.each {|k|
  17. res *= x
  18. res += k
  19. }
  20. return res
  21. }
  22. }
  23. class FactorBasePrime (p, t, lp) {
  24. has soln1 = nil
  25. has soln2 = nil
  26. has ainv = nil
  27. has p_log = p.log
  28. }
  29. func fibonacci_factorization (n, upper_bound) {
  30. var bound = (5 * n.ilog2**2)
  31. bound = upper_bound if (bound > upper_bound)
  32. loop {
  33. return nil if (bound <= 1)
  34. var B = bound.consecutive_lcm
  35. var F = B.fibmod(n)
  36. var g = gcd(F, n)
  37. if (g == n) {
  38. bound >>= 1
  39. next
  40. }
  41. if (g > 1) {
  42. return [g]
  43. }
  44. return nil
  45. }
  46. }
  47. func fast_fibonacci_factor (n, upto) {
  48. var (P, Q) = (3, 1)
  49. for k in (2 .. upto) {
  50. var (U, V) = lucasUVmod(P, Q, k, n)
  51. for t in (U, V, V-1, V+1, V-P) {
  52. var g = gcd(t, n)
  53. if (g.is_ntf(n)) {
  54. return [g]
  55. }
  56. }
  57. }
  58. return nil
  59. }
  60. # Some tuning parameters
  61. class SIQS (
  62. MASK_LIMIT = 200, # show Cn if n > MASK_LIMIT, where n ~ log_10(N)
  63. LOOK_FOR_SMALL_FACTORS = 1,
  64. TRIAL_DIVISION_LIMIT = 1_000_000,
  65. PHI_FINDER_ITERATIONS = 100_000,
  66. FERMAT_ITERATIONS = 100_000,
  67. NEAR_POWER_ITERATIONS = 1_000,
  68. PELL_ITERATIONS = 100_000,
  69. FLT_ITERATIONS = 200_000,
  70. HOLF_ITERATIONS = 100_000,
  71. MBE_ITERATIONS = 100,
  72. DOP_FACTOR_LIMIT = 1000,
  73. COP_FACTOR_LIMIT = 500,
  74. MILLER_RABIN_ITERATIONS = 100,
  75. LUCAS_MILLER_ITERATIONS = 50,
  76. SIQS_TRIAL_DIVISION_EPS = 25,
  77. SIQS_MIN_PRIME_POLYNOMIAL = 400,
  78. SIQS_MAX_PRIME_POLYNOMIAL = 4000,
  79. ) {
  80. method factor_base_primes (n, nf) {
  81. var factor_base = []
  82. 1e7.each_prime {|p|
  83. var t = n.sqrtmod(p) || next
  84. var lp = p.log2.round.int
  85. factor_base << FactorBasePrime(p, t, lp)
  86. break if (factor_base.len >= nf)
  87. }
  88. return factor_base
  89. }
  90. method create_poly (a, b, n, factor_base, first) {
  91. var b_orig = b
  92. if (2*b > a) {
  93. b = (a - b)
  94. }
  95. var g = SIQSPolynomial([a*a, 2*a*b, b*b - n], a, b_orig)
  96. var h = SIQSPolynomial([a, b])
  97. for fb in (factor_base) {
  98. next if (fb.p `divides` a)
  99. fb.ainv = a.invmod(fb.p) if first
  100. fb.soln1 = ((fb.ainv * ( fb.t - b)) % fb.p)
  101. fb.soln2 = ((fb.ainv * (-fb.t - b)) % fb.p)
  102. }
  103. return (g, h)
  104. }
  105. method find_first_poly (n, m, factor_base) {
  106. var p_min_i = nil
  107. var p_max_i = nil
  108. factor_base.each_kv { |i,fb|
  109. if (!defined(p_min_i) && (fb.p >= SIQS_MIN_PRIME_POLYNOMIAL)) {
  110. p_min_i = i
  111. }
  112. if (!defined(p_max_i) && (fb.p > SIQS_MAX_PRIME_POLYNOMIAL)) {
  113. p_max_i = i-1
  114. break
  115. }
  116. }
  117. # The following may happen if the factor base is small
  118. if (!defined(p_max_i)) {
  119. p_max_i = factor_base.end
  120. }
  121. if (!defined(p_min_i)) {
  122. p_min_i = 5
  123. }
  124. if ((p_max_i - p_min_i) < 20) {
  125. p_min_i = (p_min_i `min` 5)
  126. }
  127. var target0 = ((n.log + 2.log)/2 - m.log)
  128. var target1 = (target0 - ((log(factor_base[p_min_i].p + factor_base[p_max_i].p) - 2.log) / 2))
  129. # find q such that the product of factor_base[q_i] is approximately
  130. # sqrt(2 * n) / m; try a few different sets to find a good one
  131. var (best_q, best_a, best_ratio)
  132. 30.times {
  133. var A = 1
  134. var log_A = 0
  135. var Q = Hash()
  136. while (log_A < target1) {
  137. var p_i = 0
  138. while ((p_i == 0) || Q.exists(p_i)) {
  139. p_i = p_min_i.irand(p_max_i) # inclusive on both sides
  140. }
  141. var fb = factor_base[p_i]
  142. A *= fb.p
  143. log_A += fb.p_log
  144. Q{p_i} = fb
  145. }
  146. var ratio = exp(log_A - target0)
  147. # ratio too small seems to be not good
  148. if (!defined(best_ratio) ||
  149. (( ratio >= 0.9) && (ratio < best_ratio)) ||
  150. ((best_ratio < 0.9) && (ratio > best_ratio))
  151. ) {
  152. best_q = Q
  153. best_a = A
  154. best_ratio = ratio
  155. }
  156. }
  157. var a = best_a
  158. var b = 0
  159. var arr = []
  160. best_q.each_v { |fb|
  161. var p = fb.p
  162. var r = a/p
  163. var gamma = ((fb.t * r.invmod(p)) % p)
  164. if (gamma > (p >> 1)) {
  165. gamma = (p - gamma)
  166. }
  167. var t = r*gamma
  168. b += t
  169. arr << t
  170. }
  171. var (g, h) = self.create_poly(a, b, n, factor_base, true)
  172. return (g, h, arr)
  173. }
  174. method find_next_poly (n, factor_base, i, g, arr) {
  175. # Compute the (i+1)-th polynomials for the Self-Initializing
  176. # Quadratic Sieve, given that g is the i-th polynomial.
  177. var v = i.valuation(2)
  178. var z = ((((i >> (v+1)) & 1) == 0) ? -1 : 1)
  179. var a = g.a
  180. var b = ((g.b + 2*z*arr[v]) % a)
  181. return self.create_poly(a, b, n, factor_base, false)
  182. }
  183. method siqs_sieve (factor_base, m) {
  184. # Perform the sieving step of the SIQS. Return the sieve array.
  185. var sieve_array = (2*m + 1 -> of(0))
  186. factor_base.each {|fb|
  187. fb.p > 100 || next
  188. fb.soln1 \\ next
  189. var p = fb.p
  190. var lp = fb.lp
  191. var end = 2*m
  192. var i_start_1 = -((m + fb.soln1) // p) #/
  193. var a_start_1 = (fb.soln1 + i_start_1*p)
  194. for i in (RangeNum(a_start_1 + m, end, p)) {
  195. sieve_array[i] += lp
  196. }
  197. var i_start_2 = -((m + fb.soln2) // p) #/
  198. var a_start_2 = (fb.soln2 + i_start_2*p)
  199. for i in (RangeNum(a_start_2 + m, end, p)) {
  200. sieve_array[i] += lp
  201. }
  202. }
  203. return sieve_array
  204. }
  205. method siqs_trial_divide (n, factor_base_info) {
  206. # Determine whether the given number a can be fully factorized into
  207. # primes from the factors base. If so, return the indices of the
  208. # factors from the factor base. If not, return `nil`.
  209. if (n.is_smooth_over_prod(factor_base_info{:prod})) {
  210. var factor_index = factor_base_info{:index}
  211. return n.factor_exp.map {|p|
  212. [factor_index{p[0]}, p[1]]
  213. }
  214. }
  215. return nil
  216. }
  217. method siqs_trial_division (n, sieve_array, factor_base_info, smooth_relations, g, h, m, req_relations) {
  218. # Perform the trial division step of the Self-Initializing Quadratic Sieve.
  219. var limit = ((m.log + n.log/2)/2.log - SIQS_TRIAL_DIVISION_EPS)
  220. sieve_array.each_kv { |i,s|
  221. next if (s < limit)
  222. var x = (i - m)
  223. var gx = g.eval(x).abs
  224. var divisors_idx = self.siqs_trial_divide(gx, factor_base_info) \\ next
  225. var u = h.eval(x)
  226. var v = gx
  227. smooth_relations << [u, v, divisors_idx]
  228. if (smooth_relations.len >= req_relations) {
  229. return true
  230. }
  231. }
  232. return false
  233. }
  234. method build_matrix (factor_base, smooth_relations) {
  235. # Build the matrix for the linear algebra step of the Quadratic Sieve.
  236. var fb = factor_base.len
  237. var matrix = []
  238. smooth_relations.each {|sr|
  239. var row = fb.of(0)
  240. for u,v in (sr[2]) {
  241. row[u] = v&1
  242. }
  243. matrix << row
  244. }
  245. return matrix
  246. }
  247. method build_matrix_opt(M) {
  248. # Convert the given matrix M of 0s and 1s into a list of numbers m
  249. # that correspond to the columns of the matrix.
  250. # The j-th number encodes the j-th column of matrix M in binary:
  251. # The i-th bit of m[i] is equal to M[i][j].
  252. var m = M[0].len
  253. var cols_binary = m.of('')
  254. M.each {|mi|
  255. mi.each_kv { |j, mij|
  256. cols_binary[j] += mij
  257. }
  258. }
  259. return (cols_binary.map {|s| Number(s.flip, 2) }, M.len, m)
  260. }
  261. method find_pivot_column_opt (M, j) {
  262. # For a matrix produced by `build_matrix_opt`, return the row of
  263. # the first non-zero entry in column j, or None if no such row exists.
  264. var v = M[j]
  265. if (v == 0) {
  266. return nil
  267. }
  268. return v.valuation(2)
  269. }
  270. method solve_matrix_opt (M, n, m) {
  271. # Perform the linear algebra step of the SIQS. Perform fast
  272. # Gaussian elimination to determine pairs of perfect squares mod n.
  273. # Use the optimizations described in [1].
  274. # [1] Koç, Çetin K., and Sarath N. Arachchige. 'A Fast Algorithm for
  275. # Gaussian Elimination over GF (2) and its Implementation on the
  276. # GAPP.' Journal of Parallel and Distributed Computing 13.1
  277. # (1991): 118-122.
  278. var row_is_marked = n.of(false)
  279. var pivots = m.of(-1)
  280. for j in (m.range) {
  281. var i = self.find_pivot_column_opt(M, j) \\ next
  282. pivots[j] = i
  283. row_is_marked[i] = true
  284. for k in (m.range) {
  285. if ((k != j) && M[k].bit(i)) {
  286. M[k] ^= M[j]
  287. }
  288. }
  289. }
  290. var perf_squares = []
  291. for i in (n.range) {
  292. next if row_is_marked[i]
  293. var perfect_sq_indices = [i]
  294. for j in (m.range) {
  295. if (M[j].bit(i)) {
  296. perfect_sq_indices << pivots[j]
  297. }
  298. }
  299. perf_squares << perfect_sq_indices
  300. }
  301. return perf_squares
  302. }
  303. method calc_sqrts (n, square_indices, smooth_relations) {
  304. # Given on of the solutions returned by `solve_matrix_opt` and
  305. # the corresponding smooth relations, calculate the pair [a, b], such
  306. # that a^2 = b^2 (mod n).
  307. var r1 = 1
  308. var r2 = 1
  309. square_indices.each { |i|
  310. r1 *= smooth_relations[i][0] %= n
  311. r2 *= smooth_relations[i][1]
  312. }
  313. return (r1, r2.isqrt)
  314. }
  315. method factor_from_square (n, square_indices, smooth_relations) {
  316. # Given one of the solutions returned by `solve_matrix_opt`,
  317. # return the factor f determined by f = gcd(a - b, n), where
  318. # a, b are calculated from the solution such that a*a = b*b (mod n).
  319. # Return f, a factor of n (possibly a trivial one).
  320. var (sqrt1, sqrt2) = self.calc_sqrts(n, square_indices, smooth_relations)
  321. return gcd(sqrt1 - sqrt2, n)
  322. }
  323. method siqs_find_more_factors_gcd(numbers) {
  324. var res = Hash()
  325. numbers.each_kv { |i,n|
  326. res{n} = n
  327. for k in (i+1 .. numbers.end) {
  328. var m = numbers[k]
  329. var f = gcd(n, m)
  330. if ((f != 1) && (f != n) && (f != m)) {
  331. if (!res.exists(f)) {
  332. say "SIQS: GCD found non-trivial factor: #{f}"
  333. res{f} = f
  334. }
  335. var t1 = n//f #/
  336. var t2 = m//f #/
  337. res{t1} = t1
  338. res{t2} = t2
  339. }
  340. }
  341. }
  342. return res.values
  343. }
  344. method siqs_find_factors (n, perfect_squares, smooth_relations) {
  345. # Perform the last step of the Self-Initializing Quadratic Field.
  346. # Given the solutions returned by `solve_matrix_opt`, attempt to
  347. # identify a number of (not necessarily prime) factors of n, and
  348. # return them.
  349. var factors = []
  350. var rem = n
  351. var non_prime_factors = Hash()
  352. var prime_factors = Hash()
  353. perfect_squares.each {|square_indices|
  354. var fact = self.factor_from_square(n, square_indices, smooth_relations)
  355. next if (fact <= 1)
  356. next if (fact > rem)
  357. if (fact.is_prime) {
  358. if (!prime_factors.exists(fact)) {
  359. say "SIQS: Prime factor found: #{fact}"
  360. prime_factors{fact} = fact
  361. }
  362. rem = self.check_factor(rem, fact, factors)
  363. break if rem.is_one
  364. if (rem.is_prime) {
  365. factors << rem
  366. rem = 1
  367. break
  368. }
  369. if (defined(var root = self.check_perfect_power(rem))) {
  370. say "SIQS: Perfect power detected with root: #{root}"
  371. factors << root
  372. rem = 1
  373. break
  374. }
  375. }
  376. else {
  377. if (!non_prime_factors.exists(fact)) {
  378. say "SIQS: Composite factor found: #{fact}"
  379. non_prime_factors{fact} = fact
  380. }
  381. }
  382. }
  383. if ((rem != 1) && non_prime_factors) {
  384. non_prime_factors{rem} = rem
  385. var primes = []
  386. var composites = []
  387. self.siqs_find_more_factors_gcd(non_prime_factors.values).each {|fact|
  388. if (fact.is_prime) {
  389. primes << fact
  390. }
  391. elsif (fact > 1) {
  392. composites << fact
  393. }
  394. }
  395. for fact in (primes + composites) {
  396. if ((fact != rem) && (fact `divides` rem)) {
  397. say "SIQS: Using non-trivial factor from GCD: #{fact}"
  398. rem = self.check_factor(rem, fact, factors)
  399. }
  400. break if rem.is_one
  401. break if rem.is_prime
  402. }
  403. }
  404. if (rem != 1) {
  405. factors << rem
  406. }
  407. return factors
  408. }
  409. method siqs_choose_range (n) {
  410. # Choose m for sieving in [-m, m].
  411. exp(sqrt(n.log * n.log.log) / 2) -> round.int
  412. }
  413. method siqs_choose_nf (n) {
  414. # Choose parameters nf (sieve of factor base)
  415. exp(sqrt(n.log * n.log.log))**(2.sqrt / 4) -> round.int
  416. }
  417. method siqs_factorize (n, nf) {
  418. # Use the Self-Initializing Quadratic Sieve algorithm to identify
  419. # one or more non-trivial factors of the given number n. Return the
  420. # factors as a list.
  421. var m = self.siqs_choose_range(n)
  422. var factors = []
  423. var factor_base = self.factor_base_primes(n, nf)
  424. var factor_prod = factor_base.prod_by { .p }
  425. var factor_index = Hash(
  426. factor_base.map { .p } ~Z ^factor_base -> flat...
  427. )
  428. var factor_base_info = Hash(
  429. base => factor_base,
  430. prod => factor_prod,
  431. index => factor_index,
  432. )
  433. var smooth_relations = []
  434. var required_relations_ratio = 1
  435. var success = false
  436. var prev_cnt = 0
  437. var i_poly = 0
  438. var (g, h, arr)
  439. while (!success) {
  440. say "*** Step 1/2: Finding smooth relations ***"
  441. say "SIQS sieving range: [-#{m}, #{m}]"
  442. var required_relations = ((factor_base.len + 1) * required_relations_ratio).round.int
  443. say "Target: #{required_relations} relations."
  444. var enough_relations = false
  445. while (!enough_relations) {
  446. if (i_poly == 0) {
  447. (g, h, arr) = self.find_first_poly(n, m, factor_base);
  448. }
  449. else {
  450. (g, h) = self.find_next_poly(n, factor_base, i_poly, g, arr);
  451. }
  452. if (++i_poly >= (1 << arr.end)) {
  453. i_poly = 0
  454. }
  455. var sieve_array = self.siqs_sieve(factor_base, m)
  456. enough_relations = self.siqs_trial_division(
  457. n, sieve_array, factor_base_info, smooth_relations,
  458. g, h, m, required_relations
  459. )
  460. if ((smooth_relations.len >= required_relations) ||
  461. (smooth_relations.len > prev_cnt)
  462. ) {
  463. printf("Progress: %d/%d relations.\r", smooth_relations.len, required_relations)
  464. prev_cnt = smooth_relations.len
  465. }
  466. }
  467. say "\n\n*** Step 2/2: Linear Algebra ***"
  468. say "Building matrix for linear algebra step..."
  469. var M = self.build_matrix(factor_base, smooth_relations)
  470. var (M_opt, M_n, M_m) = self.build_matrix_opt(M)
  471. say "Finding perfect squares using Gaussian elimination...";
  472. var perfect_squares = self.solve_matrix_opt(M_opt, M_n, M_m)
  473. say "Finding factors from perfect squares...\n";
  474. factors = self.siqs_find_factors(n, perfect_squares, smooth_relations)
  475. if (factors.len >= 2) {
  476. success = true
  477. }
  478. else {
  479. say "Failed to find a solution. Finding more relations..."
  480. required_relations_ratio += 0.05
  481. }
  482. }
  483. return factors
  484. }
  485. method trial_division_small_primes (n) {
  486. # Perform trial division on the given number n using all primes up
  487. # to upper_bound. Initialize the global variable small_primes with a
  488. # list of all primes <= upper_bound. Return (factors, rem), where
  489. # factors is the list of identified prime factors of n, and rem is the
  490. # remaining factor. If rem = 1, the function terminates early, without
  491. # fully initializing small_primes.
  492. say "[*] Trial division..."
  493. var factors = n.trial_factor(TRIAL_DIVISION_LIMIT)
  494. if (factors.last.is_prime) {
  495. return (factors, 1)
  496. }
  497. var rem = factors.pop
  498. return (factors, rem)
  499. }
  500. method check_perfect_power (n) {
  501. # Check whether n is a perfect and return its perfect root.
  502. # Returns undef otherwise.
  503. if (n.is_power) {
  504. var power = n.perfect_power
  505. var root = n.perfect_root
  506. say "`-> #{n} is #{root}^#{power}"
  507. return root
  508. }
  509. return nil
  510. }
  511. method check_factor (Number n, Number i, Array factors) {
  512. while (i `divides` n) {
  513. n //= i #/
  514. factors << i
  515. if (n.is_prime) {
  516. factors << n
  517. return 1
  518. }
  519. }
  520. return n
  521. }
  522. method store_factor (Ref rem, Number f, Array factors) {
  523. f || return false
  524. f < *rem || return false
  525. f `divides` *rem || die "error: #{f} does not divide #{*rem}"
  526. if (f.is_prime) {
  527. say "`-> prime factor: #{f}"
  528. *rem = self.check_factor(*rem, f, factors)
  529. }
  530. else {
  531. say "`-> composite factor: #{f}"
  532. *rem = idiv(*rem, f)
  533. # Try to find a small factor of f
  534. var f_factor = self.find_small_factors(f, factors)
  535. if (f_factor < f) {
  536. *rem *= f_factor
  537. }
  538. else {
  539. # Use SIQS to factorize f
  540. var F = self.find_prime_factors(f)
  541. F.each {|p|
  542. if (p `divides` *rem) {
  543. *rem = self.check_factor(*rem, p, factors)
  544. break if (*rem == 1)
  545. }
  546. }
  547. }
  548. }
  549. return true
  550. }
  551. method find_small_factors (rem, factors) {
  552. # Perform up to max_iter iterations of Brent's variant of the
  553. # Pollard rho factorization algorithm to attempt to find small
  554. # prime factors. Restart the algorithm each time a factor was found.
  555. # Add all identified prime factors to factors, and return 1 if all
  556. # prime factors were found, or otherwise the remaining factor.
  557. var state = Hash(
  558. cyclotomic_check => true,
  559. fast_power_check => true,
  560. fast_fibonacci_check => true,
  561. )
  562. var len = rem.len
  563. var factorization_methods = [
  564. func {
  565. say "=> Miller-Rabin method..."
  566. miller_factor(rem, (len > 1000) ? 15 : MILLER_RABIN_ITERATIONS)
  567. },
  568. func {
  569. if (len < 3000) {
  570. say "=> Lucas-Miller method (n+1)..."
  571. lucas_factor(rem, +1, (len > 1000) ? 10 : LUCAS_MILLER_ITERATIONS)
  572. }
  573. },
  574. func {
  575. if (len < 3000) {
  576. say "=> Lucas-Miller method (n-1)..."
  577. lucas_factor(rem, -1, (len > 1000) ? 10 : LUCAS_MILLER_ITERATIONS)
  578. }
  579. },
  580. func {
  581. say "=> Phi finder method...";
  582. phi_finder_factor(rem, PHI_FINDER_ITERATIONS)
  583. },
  584. func {
  585. say "=> Fermat's method..."
  586. fermat_factor(rem, FERMAT_ITERATIONS)
  587. },
  588. func {
  589. say "=> HOLF method..."
  590. holf_factor(rem, 2*HOLF_ITERATIONS)
  591. },
  592. func {
  593. say "=> Pell factor..."
  594. pell_factor(rem, PELL_ITERATIONS)
  595. },
  596. func {
  597. say "=> Pollard p-1 (20K)..."
  598. pm1_factor(rem, 20_000)
  599. },
  600. func {
  601. say "=> Fermat's little theorem (base 2)..."
  602. flt_factor(rem, 2, (len > 1000) ? 1e4 : FLT_ITERATIONS)
  603. },
  604. func {
  605. var len_2 = (len * (log(10) / log(2)))
  606. var iter = (((len_2 * MBE_ITERATIONS) > 1_000) ? int(1_000/len_2) : MBE_ITERATIONS)
  607. if (iter > 0) {
  608. say "=> MBE method (#{iter} iter)...";
  609. mbe_factor(rem, iter)
  610. }
  611. },
  612. func {
  613. say "=> Fermat's little theorem (base 3)..."
  614. flt_factor(rem, 3, (len > 1000) ? 1e4 : FLT_ITERATIONS)
  615. },
  616. func {
  617. state{:fast_fibonacci_check} || return nil
  618. say "=> Fast Fibonacci check..."
  619. var f = fast_fibonacci_factor(rem, 5000)
  620. f || do { state{:fast_fibonacci_check} = false }
  621. f
  622. },
  623. func {
  624. state{:cyclotomic_check} || return nil
  625. say "=> Fast cyclotomic check..."
  626. var f = cyclotomic_factor(rem)
  627. f.len >= 2 || do { state{:cyclotomic_check} = false }
  628. f
  629. },
  630. func {
  631. say "=> Pollard rho (10M)..."
  632. prho_factor(rem, 1e10.isqrt)
  633. },
  634. func {
  635. say "=> Pollard p-1 (500K)..."
  636. pm1_factor(rem, 500_000)
  637. },
  638. func {
  639. say "=> ECM (600)..."
  640. ecm_factor(rem, 600, 20)
  641. },
  642. func {
  643. say "=> Williams p±1 (500K)..."
  644. pp1_factor(rem, 500_000)
  645. },
  646. func {
  647. if (len < 1000) {
  648. say "=> Chebyshev p±1 (500K)..."
  649. chebyshev_factor(rem, 500_000, 1e6.irand+2)
  650. }
  651. },
  652. func {
  653. say "=> Williams p±1 (1M)..."
  654. pp1_factor(rem, 1_000_000)
  655. },
  656. func {
  657. if (len < 1000) {
  658. say "=> Chebyshev p±1 (1M)..."
  659. chebyshev_factor(rem, 1_000_000, 1e6.irand+2)
  660. }
  661. },
  662. func {
  663. say "=> ECM (2K)..."
  664. ecm_factor(rem, 2000, 10)
  665. },
  666. func {
  667. say "=> Difference of powers..."
  668. dop_factor(rem, DOP_FACTOR_LIMIT)
  669. },
  670. func {
  671. if (len < 500) {
  672. say "=> Fibonacci p±1 (500K)..."
  673. fibonacci_factorization(rem, 500_000)
  674. }
  675. },
  676. func {
  677. say "=> Pollard-Brent rho (12M)..."
  678. pbrent_factor(rem, 1e12.isqrt)
  679. },
  680. func {
  681. say "=> Congruence of powers..."
  682. cop_factor(rem, COP_FACTOR_LIMIT)
  683. },
  684. func {
  685. say "=> Pollard p-1 (5M)..."
  686. pm1_factor(rem, 5_000_000)
  687. },
  688. func {
  689. say "=> Williams p±1 (3M)..."
  690. pp1_factor(rem, 3_000_000)
  691. },
  692. func {
  693. say "=> Pollard rho (13M)..."
  694. prho_factor(rem, 1e13.isqrt)
  695. },
  696. func {
  697. say "=> ECM (160K)..."
  698. ecm_factor(rem, 160_000, 80)
  699. },
  700. ]
  701. loop {
  702. break if (rem <= 1)
  703. if (rem.is_prime) {
  704. factors << rem
  705. rem = 1
  706. break
  707. }
  708. len = rem.len
  709. if ((len >= 25) && (len <= 30)) { # factorize with SIQS directly
  710. return rem
  711. }
  712. printf("\n[*] Factoring %s (%s digits)...\n\n", (len > MASK_LIMIT ? "C#{len}" : rem), len)
  713. say "=> Perfect power check..."
  714. var f = self.check_perfect_power(rem)
  715. if (defined(f)) {
  716. var pow = rem.perfect_power
  717. var r = self.factorize(f)
  718. factors << (r*pow)...
  719. return 1
  720. }
  721. var found_factor = false
  722. var end = factorization_methods.end
  723. for (var i = 0; i <= end; ++i) {
  724. var f = factorization_methods[i].call || next
  725. f.each {|p|
  726. if (self.store_factor(\rem, p, factors)) {
  727. found_factor = true
  728. }
  729. }
  730. if (found_factor) {
  731. factorization_methods.unshift(factorization_methods.pop_at(i))
  732. break
  733. }
  734. else {
  735. factorization_methods.push(factorization_methods.pop_at(i))
  736. --i
  737. --end
  738. }
  739. }
  740. found_factor && next
  741. break
  742. }
  743. return rem
  744. }
  745. method find_prime_factors(n) {
  746. # Return one or more prime factors of the given number n. Assume
  747. # that n is not a prime and does not have very small factors, and that
  748. # the global small_primes has already been initialized. Do not return
  749. # duplicate factors.
  750. var factors = Hash()
  751. if (defined(var root = self.check_perfect_power(n))) {
  752. factors{root} = root
  753. }
  754. else {
  755. var digits = n.len
  756. say "\n[*] Using SIQS to factorize #{n} (#{digits} digits)...\n"
  757. var nf = self.siqs_choose_nf(n)
  758. var sf = self.siqs_factorize(n, nf)
  759. factors{sf...} = sf...
  760. }
  761. var prime_factors = []
  762. factors.each_v { |f|
  763. prime_factors += self.find_all_prime_factors(f)
  764. }
  765. return prime_factors
  766. }
  767. method verify_prime_factors (Number n, Array factors) {
  768. factors.prod == n || die "product of factors != n"
  769. factors.each {|p|
  770. p.is_prime || die "not prime detected: #{p}"
  771. }
  772. factors.sort
  773. }
  774. method find_all_prime_factors (n) {
  775. # Return all prime factors of the given number n. Assume that n
  776. # does not have very small factors and that the global small_primes
  777. # has already been initialized.
  778. var rem = n
  779. var factors = []
  780. while (rem > 1) {
  781. if (rem.is_prime) {
  782. factors << rem
  783. break
  784. }
  785. self.find_prime_factors(rem).each {|f|
  786. #~ rem != f || die 'error'
  787. #~ rem % f == 0 || die 'error'
  788. #~ is_prime(f) || die 'error'
  789. rem = self.check_factor(rem, f, factors);
  790. break if rem.is_one
  791. }
  792. }
  793. return factors
  794. }
  795. method factorize (n) {
  796. # Factorize the given integer n >= 1 into its prime factors.
  797. var orig = n
  798. if (n < 1) {
  799. die "Number needs to be an integer >= 1"
  800. }
  801. var len = n.len
  802. printf("\n[*] Factoring %s (%d digits)...\n", (len > MASK_LIMIT ? "C#{len}" : n), len)
  803. return [] if n.is_one
  804. return [n] if n.is_prime
  805. with (self.check_perfect_power(n)) {|root|
  806. var pow = n.perfect_power
  807. var factors = self.factorize(root)
  808. return self.verify_prime_factors(orig, factors*pow)
  809. }
  810. var divisors = (len>=30 ? Math.gcd_factors(
  811. n, n.dop_factor(DOP_FACTOR_LIMIT) + n.cop_factor(COP_FACTOR_LIMIT)
  812. ).first(-1) : [])
  813. if (divisors) {
  814. say "[*] Divisors found so far: #{divisors.join(', ')}";
  815. var composites = []
  816. var factors = []
  817. divisors.each {|d|
  818. d > 1 || next
  819. if (d.is_prime) {
  820. factors << d
  821. }
  822. else {
  823. composites << d
  824. }
  825. }
  826. factors << composites.reverse.map { self.factorize(_) }.flat...
  827. var rem = (orig / factors.prod)
  828. if (rem.is_prime) {
  829. factors << rem
  830. }
  831. elsif (rem > 1) {
  832. factors << self.factorize(rem)...
  833. }
  834. return self.verify_prime_factors(orig, factors)
  835. }
  836. var (factors, rem) = self.trial_division_small_primes(n)
  837. if (factors) {
  838. say "[*] Prime factors found so far: #{factors.join(', ')}"
  839. }
  840. else {
  841. say "[*] No small factors found..."
  842. }
  843. if (rem != 1) {
  844. if (LOOK_FOR_SMALL_FACTORS) {
  845. say "[*] Trying to find more small factors..."
  846. rem = self.find_small_factors(rem, factors)
  847. }
  848. else {
  849. say "[*] Skipping the search for more small factors..."
  850. }
  851. if (rem > 1) {
  852. factors += self.find_all_prime_factors(rem)
  853. }
  854. }
  855. factors.sort!
  856. assert_eq(factors.prod, n)
  857. factors.each {|p|
  858. assert(p.is_prime, "non-prime detected: #{p}")
  859. }
  860. return self.verify_prime_factors(orig, factors)
  861. }
  862. }
  863. if (ARGV) {
  864. var n = Number(ARGV[0])
  865. if (n.is_nan) {
  866. # evaluate the expression using PARI/GP
  867. n = Num(`echo #{ARGV[0].escape} | gp -q -f`)
  868. }
  869. if (n.is_nan) {
  870. die "Invalid expression: #{ARGV[0].dump}"
  871. }
  872. var siqs = SIQS()
  873. say "\nPrime factors: #{siqs.factorize(n)}"
  874. }
  875. else {
  876. say "usage: #{__MAIN__} <N>"
  877. }