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 if it exists DROP FUNCTION IF EXISTS fast_exponentiation(DOUBLE PRECISION, INTEGER); -- Create a new function CREATE OR REPLACE FUNCTION fast_exponentiation( base DOUBLE PRECISION, exponent INTEGER ) RETURNS DOUBLE PRECISION AS $$ DECLARE result DOUBLE PRECISION := 1.0; abs_exponent INTEGER := ABS(exponent); BEGIN -- 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 base := 1.0 / base; END IF; WHILE abs_exponent > 0 LOOP IF abs_exponent % 2 = 1 THEN result := result * base; END IF; base := base * base; abs_exponent := abs_exponent / 2; END LOOP; RETURN result; END; $$ LANGUAGE plpgsql;

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

Copy Clear