Hi! Could we please enable some services and cookies to improve your experience and our website?

SQLize | PHPize | SQLtest

Online Sandbox for SQL and PHP: Write, Run, Test, and Share SQL Queries and PHP Code

A A A
Login    Share code      Blog   FAQ
Copy Format Clear
-- DROP the function first if it exists DROP FUNCTION IF EXISTS fast_exponentiation; DELIMITER $$ CREATE FUNCTION fast_exponentiation(base DOUBLE, exponent INT) RETURNS DOUBLE DETERMINISTIC BEGIN DECLARE result DOUBLE DEFAULT 1.0; DECLARE abs_exponent INT; SET abs_exponent = ABS(exponent); -- Handle 0^0 IF base = 0 AND exponent = 0 THEN RETURN 1.0; END IF; -- Handle 0^positive IF base = 0 THEN RETURN 0.0; END IF; -- Handle negative exponent IF exponent < 0 THEN SET base = 1.0 / base; END IF; WHILE abs_exponent > 0 DO IF MOD(abs_exponent, 2) = 1 THEN SET result = result * base; END IF; SET base = base * base; SET abs_exponent = FLOOR(abs_exponent / 2); END WHILE; RETURN result; END$$ DELIMITER ; SELECT fast_exponentiation(2, -3); -- Expected: 0.125 SELECT fast_exponentiation(-2, 4); -- Expected: 16 SELECT fast_exponentiation(0, 0); -- Expected: 1 SELECT fast_exponentiation(-3, 3); -- Expected: -27

Stuck with a problem? Got Error? Ask AI support!

Copy Clear