Project

General

Profile

Actions

Feature #12675

closed

Code simplification and readability for prime_division method in prime.rb

Added by jzakiya (Jabari Zakiya) over 7 years ago. Updated over 2 years ago.

Status:
Closed
Assignee:
-
Target version:
-
[ruby-core:76865]

Description

I believe the following code simplification for the prime_division
method in prime.rb makes it more readable as English, thus more
understandable, while also significantly more concise in terms of
lines-of-code (25 vs 16), and may I dare say, more idiomatic, and beautiful.

  def prime_division(value, generator = Prime::Generator23.new)
    raise ZeroDivisionError if value == 0
    if value < 0
      value = -value
      pv = [[-1, 1]]
    else
      pv = []
    end
    generator.each do |prime|
      count = 0
      while (value1, mod = value.divmod(prime)
             mod) == 0
        value = value1
        count += 1
      end
      if count != 0
        pv.push [prime, count]
      end
      break if value1 <= prime
    end
    if value > 1
      pv.push [value, 1]
    end
    pv
  end
  
  def prime_division(value, generator = Prime::Generator23.new)
    raise ZeroDivisionError if value == 0
    pv = value < 0 ? [[-1, 1]] : []
    value = value.abs
    generator.each do |prime|
      count = 0
      while (value1, mod = value.divmod(prime); mod) == 0 
        value = value1
        count +=1 
      end
      pv.push [prime, count] unless count == 0
      break if prime > value1
    end
    pv.push [value, 1] if value > 1                 
    pv
  end

Updated by hsbt (Hiroshi SHIBATA) over 2 years ago

  • Tracker changed from Misc to Feature
  • Status changed from Open to Closed

prime.rb was extracted from ruby repository to https://github.com/ruby/prime. If you still interested in this, Can you file it to ruby/prime repo? Thanks.

Actions

Also available in: Atom PDF

Like0
Like0