Jump to content

Ethiopian multiplication: Difference between revisions

(→‎{{header|LOLCODE}}: Named functions is from the 1.3 proposal, not 1.2 spec)
Line 3,049:
Iterative and recursive implementations here.
I've chosen to highlight the example 20*5 which I think is more illustrative.
<lang ruby>def evenhalve(x); x.even?;/2 end
def halvedouble(x); x/*2; end
def double(x); x*2; end
 
# iterative
def ethopian_multiplyethiopian_multiply(a, b)
product = 0
while a >= 1
p [a, b, even(a).even? ? "STRIKE" : "KEEP"] if $DEBUG
product += b if notunless a.even(a)?
a = halve(a)
b = double(b)
Line 3,066 ⟶ 3,065:
 
# recursive
def rec_ethopian_multiplyrec_ethiopian_multiply(a, b)
return 0 if a < 1
p [a, b, even(a).even? ? "STRIKE" : "KEEP"] if $DEBUG
(even(a).even? ? 0 : b) + rec_ethopian_multiplyrec_ethiopian_multiply(halve(a), double(b))
end
 
$DEBUG = true # $DEBUG also set to true if "-d" option given
a, b = 20, 5
puts "#{a} * #{b} = #{ethopian_multiplyethiopian_multiply(a,b)}"; puts</lang>
 
{{out}}
Output:
<pre>[20, 5, "STRIKE"]
[20, 5, "STRIKE"]
[10, 10, "STRIKE"]
[5, 20, "KEEP"]
Line 3,100:
def test_rec6; assert_equal(0, rec_ethopian_multiply(0,5)); end
end</lang>
<pre>LoadedRun suiteoptions: ethopian
 
Started
# Running tests:
 
............
Finished tests in 0.001014001s, 857.0816 tests/s, 857.0816 secondsassertions/s.
 
12 tests, 12 assertions, 0 failures, 0 errors</pre>, 0 skips
 
ruby -v: ruby 2.0.0p247 (2013-06-27) [i386-mingw32]
12 tests, 12 assertions, 0 failures, 0 errors</pre>
</pre>
 
=={{header|Scala}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.