Search code examples
rubyalgorithmprimesprime-factoringfactorization

Array in an odd order


I wrote this to find the prime factorization of a number num. It gives the right answers (for example, 2, 3, 2, 3, 2 for num 72), but it comes out in an odd order. I can't figure out why. I was wondering if somebody sees something I don't.

$primes = [2]
$factors = []
num = 72
max = num

def isprime(n)
 $primes.each do |x|
  if n % x == 0 then
   return
  end
 end
 $primes.push(n)
 return
end

i = 3
while i <= max
 isprime(i)
 i += 1
end

while !($primes.include?(num))
 $primes.each do |x|
  if num % x == 0 then
   $factors.push(x)
   num /= x
  end
 end
end
$factors.push(num)

puts $factors

Solution

  • You need to break the $primes.each loop as soon as you find a factor, or it'll complete the loop each time.

    while !($primes.include?(num))
      $primes.each do |x|
        if num % x == 0 then
          $factors.push(x)
          num /= x
          break
        end
      end
    end
    $factors.push(num)
    

    P.S: I've just kept to the algorithmic side and ignored the Ruby side.