Ethiopian multiplication: Difference between revisions
Content added Content deleted
(→{{header|LOLCODE}}: Named functions is from the 1.3 proposal, not 1.2 spec) |
|||
Line 3,049: | Line 3,049: | ||
Iterative and recursive implementations here. |
Iterative and recursive implementations here. |
||
I've chosen to highlight the example 20*5 which I think is more illustrative. |
I've chosen to highlight the example 20*5 which I think is more illustrative. |
||
<lang ruby>def |
<lang ruby>def halve(x) x/2 end |
||
def |
def double(x) x*2 end |
||
def double(x); x*2; end |
|||
# iterative |
# iterative |
||
def |
def ethiopian_multiply(a, b) |
||
product = 0 |
product = 0 |
||
while a >= 1 |
while a >= 1 |
||
p [a, b, |
p [a, b, a.even? ? "STRIKE" : "KEEP"] if $DEBUG |
||
product += b |
product += b unless a.even? |
||
a = halve(a) |
a = halve(a) |
||
b = double(b) |
b = double(b) |
||
Line 3,066: | Line 3,065: | ||
# recursive |
# recursive |
||
def |
def rec_ethiopian_multiply(a, b) |
||
return 0 if a < 1 |
return 0 if a < 1 |
||
p [a, b, |
p [a, b, a.even? ? "STRIKE" : "KEEP"] if $DEBUG |
||
(a.even? ? 0 : b) + rec_ethiopian_multiply(halve(a), double(b)) |
|||
end |
end |
||
$DEBUG = true # $DEBUG also set to true if "-d" option given |
$DEBUG = true # $DEBUG also set to true if "-d" option given |
||
a, b = 20, 5 |
a, b = 20, 5 |
||
puts "#{a} * #{b} = #{ |
puts "#{a} * #{b} = #{ethiopian_multiply(a,b)}"; puts</lang> |
||
{{out}} |
|||
Output: |
|||
<pre> |
<pre> |
||
[20, 5, "STRIKE"] |
|||
[10, 10, "STRIKE"] |
[10, 10, "STRIKE"] |
||
[5, 20, "KEEP"] |
[5, 20, "KEEP"] |
||
Line 3,100: | Line 3,100: | ||
def test_rec6; assert_equal(0, rec_ethopian_multiply(0,5)); end |
def test_rec6; assert_equal(0, rec_ethopian_multiply(0,5)); end |
||
end</lang> |
end</lang> |
||
<pre> |
<pre>Run options: |
||
Started |
|||
# Running tests: |
|||
............ |
............ |
||
Finished in 0. |
Finished tests in 0.014001s, 857.0816 tests/s, 857.0816 assertions/s. |
||
⚫ | |||
ruby -v: ruby 2.0.0p247 (2013-06-27) [i386-mingw32] |
|||
⚫ | |||
</pre> |
|||
=={{header|Scala}}== |
=={{header|Scala}}== |