Ethiopian multiplication: Difference between revisions
Content added Content deleted
(+ version for pl/pgsql) |
|||
Line 903: | Line 903: | ||
/ |
/ |
||
</lang> |
</lang> |
||
=={{header|PL/pgSQL}}== |
|||
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 sql> |
|||
SELECT ethiopian_multiplication(17, 34); |
|||
</lang> |
|||
<lang text> |
|||
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}}== |
=={{header|PowerShell}}== |