Module: Primes::Utils

Defined in:
lib/primes/utils.rb,
lib/primes/utils/version.rb

Constant Summary collapse

VERSION =
"1.0.0"

Instance Method Summary collapse

Instance Method Details

#factors(p = 13) ⇒ Object Also known as: prime_division

P13 is default prime generator here



16
17
18
19
# File 'lib/primes/utils.rb', line 16

def factors(p=0) # p is unused dummy variable for method consistency
  factors = `factor #{self.abs}`.split(' ')[1..-1].map {|i| i.to_i}
  h = Hash.new(0); factors.each {|f| h[f] +=1}; h.to_a.sort
end

#prime?Boolean

use pure ruby versions for platforms without cli command ‘factor’

Returns:

  • (Boolean)


25
26
27
# File 'lib/primes/utils.rb', line 25

def prime?
  `factor #{self.abs}`.split(' ').size == 2
end

#primemr?(k = 20) ⇒ Boolean

increase k for more reliability

Returns:

  • (Boolean)


220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/primes/utils.rb', line 220

def primemr?(k=20) # increase k for more reliability
  n = self.abs
  return true  if n == 2 or n == 3
  return false if n % 6 != 1 && n % 6 != 5 or n == 1

  d = n - 1
  s = 0
  (d >>= 1; s += 1) while d.even?
  k.times do
    a = 2 + rand(n-4)
    x = a.to_bn.mod_exp(d,n)       #x = (a**d) mod n
    next if x == 1 or x == n-1
    (s-1).times do
      x = x.mod_exp(2,n)           #x = (x**2) mod n
      return false if x == 1
      break if x == n-1
    end
    return false if x != n-1
  end
  true  # with high probability
end

#primenth(p = 11) ⇒ Object Also known as: nthprime

return value of nth prime



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/primes/utils.rb', line 94

def primenth(p=11) # return value of nth prime
  # Return value of nth prime
  # Uses sozP11 Sieve of Zakiya (SoZ) as default prime sieve

  seeds  = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41]
  primes = []

  n = self.abs # the desired nth prime
  return seeds[n-1] if n < 14
  numb = 22*n  # approx value need to check primes up to

  # find primes <= Pn, compute modPn then Prime Gen residues for Pn
  primes = seeds[0..seeds.index(p)]; mod = primes.reduce(:*)
  residues=[1]; 3.step(mod,2) {|i| residues << i if mod.gcd(i) == 1}
  residues << mod+1; rescnt = residues.size-1

  num = numb-1 | 1              # if N even number then subtract 1
  k=num/mod; modk = mod*k; r=1  # kth residue group; base num value
  while num >= modk+residues[r]; r += 1 end # compute extra prms size
  maxprms = k*rescnt + r-1      # max size of prime candidates array
  prms=Array.new(maxprms,true)  # set all prime candidates to True

  # array of residues offsets to compute nonprimes positions in prms
  pos =[]; rescnt.times {|i| pos[residues[i]] = i-1};

  # sieve (SoZ) to eliminate nonprimes from prms
  sqrtN = Math.sqrt(num).to_i
  modk,r,k=0,0,0
  prms.each do |prime|
    r +=1; if r > rescnt; r=1; modk +=mod; k +=1 end
    next unless prime
    res_r = residues[r]
    prime = modk + res_r
    break if prime > sqrtN
    prmstep = prime * rescnt
    residues[1..-1].each do |ri|
      # compute (prime * (modk + ri)) position index in prms
      kk,rr  = (res_r * ri).divmod mod  # residues product res[group|track]
      nonprm = (k*(prime + ri) + kk)*rescnt + pos[rr]
      while nonprm < maxprms; prms[nonprm]=nil; nonprm +=prmstep end
    end
  end
  # the prms array now has all the primes positions for primes r1..N
  # find the nth prime and output it
  count = primes.size
  modk,r=0,0
  prms.each do |prime|
    r +=1; if r > rescnt; r=1; modk +=mod end
    count +=1 if prime
    return modk+residues[r] if count == n
  end
end

#primes(start_num = 0) ⇒ Object



149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/primes/utils.rb', line 149

def primes(start_num=0)
  # Find primes between a number range: end_num - start_num
  # Use as: end_num.primes(start_num) or end_num.primes
  # If start_num omitted, will find all primes <= end_num
  # If start_num > self, values are switched to continue
  # Output is an array of the primes within the given range
  # To find count of these primes do: end_num.primes(start_num).size
  # This method uses the P13 Strictly Prime (SP) Prime Generator

  num = self.abs;  start_num = start_num.abs
  num, start_num = start_num, num  if start_num > num

  primes = [2,3,5,7,11,13]      # P13 excluded primes lists

  return primes.select {|p| p >= start_num && p <= num} if num <= 13

  mod = 30030                   # P13 modulus value 2*3*5*7*11*13

  residues=[1]; 17.step(mod,2) {|i| residues << i if mod.gcd(i) == 1}
  rescnt = residues.size        # number of residues
  residues << mod+1             # to make algorithm easier

  num = num-1 | 1               # if N even number then subtract 1
  k=num/mod; modk = mod*k; r=1  # kth residue group; base num value
  while num >= modk+residues[r]; r += 1 end # compute extra prms size
  maxprms = k*rescnt + r-1      # max size of prime candidates array
  prms=Array.new(maxprms,true)  # set all prime candidates to True

  # hash of residues offsets to compute nonprimes positions in prms
  pos =[]; rescnt.times {|i| pos[residues[i]] = i-1};

  # sieve (SoZ) to eliminate nonprimes from prms
  sqrtN= Math.sqrt(num).to_i
  modk,r,k=0,0,0
  prms.each do |prime|
    r +=1; if r > rescnt; r=1; modk +=mod; k +=1 end
    next unless prime
    res_r = residues[r]
    prime = modk + res_r
    break if prime > sqrtN
    prmstep = prime * rescnt
    residues[1..-1].each do |ri|
      # compute (prime * (modk + ri)) position index in prms
      kk,rr  = (res_r * ri).divmod mod  # residues product res[group|track]
      nonprm = (k*(prime + ri) + kk)*rescnt + pos[rr] # 1st prime multiple
      while nonprm < maxprms; prms[nonprm]=nil; nonprm +=prmstep end
    end
  end
  # the prms array now has all the primes positions for primes r1..N
  primes = start_num <= 13 ? primes.drop_while {|p| p < start_num} : []
  k = start_num / mod
  modk = mod*k
  m = rescnt*k
  r = 0
  while m < maxprms
    r +=1; if r > rescnt; r=1; modk +=mod end
    if prms[m]
      prime = modk + residues[r]
	  primes << prime if prime >= start_num
    end
    m +=1
  end
  primes
end