Module: Primes::Utils

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

Constant Summary collapse

VERSION =
"1.1.1"

Instance Method Summary collapse

Instance Method Details

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

P13 is default prime generator here



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

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)


32
33
34
# File 'lib/primes/utils.rb', line 32

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

#primemr?(k = 20) ⇒ Boolean

increase k for more reliability

Returns:

  • (Boolean)


227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/primes/utils.rb', line 227

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



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
146
147
148
149
150
151
152
# File 'lib/primes/utils.rb', line 101

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]
  primes = []

  n = self.abs                  # the desired nth prime
  return n != 0 ? seeds[n-1] : 0  if n < seeds.size

  # compute approximate value of (>) nth prime to count up to
  numb = (n*(Math.log(n)+2)).to_i

  # 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
  # count up to nth prime, compute value from address, and output
  prmcnt = primes.size          # number of primes up to Pn
  m=0
  while prmcnt < n; prmcnt +=1 if prms[m]; m +=1 end
  k,rr = m.divmod rescnt
  return (mod*k + residues[rr])
end

#primes(start_num = 0) ⇒ Object



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
213
214
215
216
217
218
219
# File 'lib/primes/utils.rb', line 156

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 (PG)

  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
  plast  = primes.last          # last prime in primes
  return primes.select {|p| p >= start_num && p <= num} if num <= plast

  mod = primes.reduce(:*)       # P13 modulus value 2*3*5*7*11*13

  residues=[1]; plast.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 <= plast ? primes.drop_while {|p| p < start_num} : []
  k = (start_num-2).abs/mod  # start_num's residue group value
  modk = mod*k               # start_num's mod group value
  m = rescnt*k               # number of prms elements up to kth resgroup
  r = 0                      # begin processing at start of resgroup
  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