We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
CREATE PROCEDURE prime(I INT)
BEGIN
SET @a = I; -- Upper limit for prime number generation
SET @b = 1; -- Starting number
SET @prime = ''; -- String to store prime numbers
-- Loop through numbers from 1 to I
WHILE @b <= @a DO
SET @c = 0; -- Counter for divisors
SET @d = 1; -- Starting divisor
-- Check divisors of @b
WHILE @d <= @b DO
IF @b % @d = 0 THEN
SET @c = @c + 1; -- Increase divisor count
END IF;
SET @d = @d + 1; -- Next divisor
END WHILE;
-- If @b is prime (exactly 2 divisors)
IF @c = 2 THEN
IF @prime != '' THEN
SET @prime = CONCAT(@prime, '&', @b); -- Append prime number to string
ELSE
SET @prime = @b; -- Initialize the string with the first prime
END IF;
END IF;
SET @b = @b + 1; -- Next number
END WHILE;
SELECT @prime; -- Return the string of prime numbers
END $$
DELIMITER ;
-- Call the procedure with an input value
CALL prime(1000);
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Print Prime Numbers
You are viewing a single comment's thread. Return to all comments →
SQL Stored Procedure
Procedure to Generate Prime Numbers
Definition
`sql DELIMITER $$
CREATE PROCEDURE prime(I INT) BEGIN SET @a = I; -- Upper limit for prime number generation SET @b = 1; -- Starting number SET @prime = ''; -- String to store prime numbers
END $$
DELIMITER ;
-- Call the procedure with an input value CALL prime(1000);