 # Kata @\$\$-kick! Prime Factors

I’m trying to re-write the prime factors kata without using the Prime
library. About to go berserk with frustration, too.

I’ve tried a mess of different techniques and puts’d all over the place
to “see” a solution, but have just been looking at it too long now.

Right now the code below will iterate over a range, find the factors,
to array.

But I’m missing something to reduce the factors to actual prime factors.
: \

The following produces the answer I’m looking for, with the prime
library (for
guidance).

require ‘prime’

def prime(n)
n.prime_division.map { |base, exp| [base]*exp }.flatten
end

Any input on the below?? Thanks in advance for your time & help

in an array.

def primes(n)
puts
puts

# initialize the array to add the prime factors

prime_factors = []
factor = n

# iterate over range, up to sqrt integer

(2).upto(Math.sqrt(factor).to_i). each do |divisor|

# Math.sqrt(factor).to_i.downto(2).each do |divisor|

``````puts "Finding primes from #{divisor} to #{factor}."
puts
puts "Checking now if #{divisor} is a factor."

if factor % divisor == 0

puts "--> #{factor} is divisible by #{divisor}."

prime_factors << divisor

puts "Factors array now set: #{prime_factors.inspect}"

quotient = factor / divisor

factor = quotient

end #/if loop
``````

end #/do
puts
puts “Exiting loop; #{factor} is the last quotient to’ve passed if
statement.”
prime_factors << factor
p prime_factors
end

# primes(10) # should print [2,5]

primes(8) # should print [2,2,2] --> currently prints [2,4]

This will get you the answers you want BUT it is not doing the correct
thing.
Your trial divisors only need to be primes.

in
an array.

def primes(n)
puts
puts

# initialize the array to add the prime factors

prime_factors = []
factor = n
divisor = 2
while divisor*divisor <= factor

# iterate over range, up to sqrt integer

#(2).upto(Math.sqrt(factor).to_i). each do |divisor|

# Math.sqrt(factor).to_i.downto(2).each do |divisor|

``````puts "Finding primes from #{divisor} to #{factor}."
puts
puts "Checking now if #{divisor} is a factor."

while factor % divisor == 0

puts "--> #{factor} is divisible by #{divisor}."

prime_factors << divisor

puts "Factors array now set: #{prime_factors.inspect}"

quotient = factor / divisor

factor = quotient

end #/if loop
divisor += 1
``````

end #/do
puts
puts “Exiting loop; #{factor} is the last quotient to’ve passed if
statement.”
if factor > 1
prime_factors << factor
end
p prime_factors
end

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.