[ruby-core:104702] [Ruby master Feature#12675] Code simplification and readability for prime_division method in prime.rb
From:
hsbt@...
Date:
2021-07-27 11:56:46 UTC
List:
ruby-core #104702
Issue #12675 has been updated by hsbt (Hiroshi SHIBATA).
Status changed from Open to Closed
Tracker changed from Misc to Feature
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.
----------------------------------------
Feature #12675: Code simplification and readability for prime_division method in prime.rb
https://bugs.ruby-lang.org/issues/12675#change-93028
* Author: jzakiya (Jabari Zakiya)
* Status: Closed
* Priority: Normal
----------------------------------------
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
```
--
https://bugs.ruby-lang.org/
Unsubscribe: <mailto:ruby-core-request@ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>