Search Postgresql Archives

Function to return list of all prime numbers in range

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Title: Function to return list of all prime numbers in range

My apologies if this is the wrong mailing list.

I've created a function that returns a list of all prime numbers in a range.
eg: SELECT public.all_prime(190, 223);

191,193,197,199,211,223

I'd like to submit this the the contrib lib, but I could not find the correct
email list. Use as you wish.

The code is below.
==================================================================================
CREATE OR REPLACE FUNCTION public.all_prime(INT4, INT4)
RETURNS TEXT AS
-- Returns a list of all prime numbers in the range of $1 to $2
-- Contibuted by Melvin Davidson
-- Computer & Communication Technologies, Inc.
-- mdavidson@xxxxxxxxx
$BODY$
DECLARE
  v_start               ALIAS FOR $1;
  v_end         ALIAS FOR $2;
  v_test                INT4;
  v_divisor     INT4;
  v_prime_list  TEXT DEFAULT '';
  v_msg         TEXT;
BEGIN

        v_test = v_start;

        WHILE (v_test <= v_end) LOOP

                v_divisor = 2;
                WHILE (v_divisor <= v_test) LOOP

                        IF mod(v_test, v_divisor) = 0 AND v_divisor < v_test THEN
                                EXIT;
                        ELSE
                                IF mod(v_test, v_divisor) = 0 AND v_divisor = v_test THEN
                                        IF v_prime_list > '' THEN
                                                v_prime_list = v_prime_list ||  ',';
                                        END IF;
                                        v_prime_list = v_prime_list || v_test::text;
                                END IF;
                        END IF;
                        v_divisor = v_divisor +1;

                END LOOP;
                v_test = v_test + 1;

        END LOOP;

        RETURN v_prime_list;
END;
$BODY$
  LANGUAGE 'plpgsql' VOLATILE;

GRANT EXECUTE ON FUNCTION public.all_prime(INT4, INT4) TO public;
COMMENT ON FUNCTION public.all_prime(INT4, INT4) IS 'Returns list of all prime numbers from $1 to $2';
==================================================================================


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[Index of Archives]     [Postgresql Jobs]     [Postgresql Admin]     [Postgresql Performance]     [Linux Clusters]     [PHP Home]     [PHP on Windows]     [Kernel Newbies]     [PHP Classes]     [PHP Books]     [PHP Databases]     [Postgresql & PHP]     [Yosemite]
  Powered by Linux