Last active
June 4, 2016 16:51
-
-
Save alibitek/df5033fa21d4bf45a13f39949d701843 to your computer and use it in GitHub Desktop.
MySQL Sieve of Eratosthenes prime number generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DELIMITER $$ | |
DROP PROCEDURE IF EXISTS prime $$ | |
CREATE PROCEDURE prime (n INT, OUT res varchar(8000)) | |
BEGIN | |
DECLARE i smallint DEFAULT 2; | |
DECLARE j smallint; | |
DECLARE isPrime bit; | |
DECLARE result varchar(8000) DEFAULT ''; | |
WHILE i < n | |
DO | |
SET isPrime = 1; | |
SET j = 2; | |
primalityTestLoop: REPEAT | |
IF i != j and i % j = 0 | |
THEN | |
SET isPrime = 0; | |
LEAVE primalityTestLoop; | |
END IF; | |
SET j = j + 1; | |
UNTIL j * j > i | |
END REPEAT primalityTestLoop; | |
IF isPrime = 1 | |
THEN | |
SET result = concat(result, CAST(i AS char(4)), '&'); | |
END IF; | |
SET i = i + 1; | |
END WHILE; | |
SET res = LEFT(result, length(result) - 1); | |
END $$ | |
DELIMITER ; | |
SET @res = ''; | |
CALL prime(1000, @res); | |
SELECT @res; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment