Ethiopian multiplication: Difference between revisions

Removed all PL/pgSQL and second R example marked incorrect for several months.
(→‎{{header|Oz}}: improved readibility)
(Removed all PL/pgSQL and second R example marked incorrect for several months.)
Line 1,231:
end;
/</lang>
 
 
 
=={{header|PL/pgSQL}}==
{{incorrect|PL/pgSQL|The example is to have separate functions for doubling, halving, and checking if a number is even.}}
Everything encapsulated in one function.
 
<lang plpgsql>CREATE OR REPLACE FUNCTION ethiopian_multiplication(multiplier int, multiplicant int) RETURNS int AS $BODY$
-- works at least on PostgreSQL 8.3, should work in older versions as well
DECLARE
sum integer := 0;
plier integer := abs(multiplier);
plicant integer := abs(multiplicant);
BEGIN
-- handling 0 values
IF (multiplier = 0 OR multiplicant = 0) THEN
RAISE NOTICE 'One operand is 0. Result 0.';
RETURN 0;
END IF;
-- running until left operand equals 1
WHILE plier >= 1 LOOP
-- is left operand even?
IF plier % 2 = 0 THEN
-- yes, strike this row
RAISE NOTICE '%, % STRIKE', plier, plicant;
ELSE
-- no, add this row to sum
RAISE NOTICE '%, % KEEP', plier, plicant;
sum = sum + plicant;
END IF;
-- halve left argument
plier = floor(plier/2);
-- double left argument
plicant = plicant*2;
END LOOP;
-- handling negative arguments
IF (multiplier < 0 AND multiplicant > 0) OR (multiplier > 0 AND multiplicant < 0) THEN
RAISE NOTICE 'Handling negative operands. Invert result.';
sum = 0 - sum;
END IF;
RETURN sum;
END;
$BODY$ LANGUAGE 'plpgsql';</lang>
 
<lang plpgsql>SELECT ethiopian_multiplication(17, 34);</lang>
 
<lang plpgsql>NOTICE: 17, 34 KEEP
NOTICE: 8, 68 STRIKE
NOTICE: 4, 136 STRIKE
NOTICE: 2, 272 STRIKE
NOTICE: 1, 544 KEEP
ethiopian_multiplication
--------------------------
578
(1 row)</lang>
 
=={{header|PowerShell}}==
Line 1,405 ⟶ 1,350:
 
print(ethiopicmult(17, 34, TRUE))</lang>
 
Another interesting implementation could be
{{incorrect|R|The task specifies that examples should have separate functions for doubling, halving, and checking if a number is even.}}
<lang R>ethiopicmult <- function(a, b) {
plier <- c(a)
plicand <- c(b)
while( plier[ length(plier) ] > 1 ) {
plier <- c(plier, floor(plier[length(plier)]/2))
plicand <- c(plicand, plicand[length(plicand)]*2)
}
return( sum(plicand[ plier %% 2 != 0]) )
}</lang>
 
=={{header|Ruby}}==
Anonymous user