Data Science Hub
  • Data Science Hub
  • STATISTICS
    • Introduction
    • Fundamentals
      • Data Types
      • Central Tendency, Asymmetry, and Variability
      • Sampling
      • Confidence Interval
      • Hypothesis Testing
    • Distributions
      • Exponential Distribution
    • A/B Testing
      • Sample Size Calculation
      • Multiple Testing
  • Database
    • Database Fundamentals
    • Database Management Systems
    • Data Warehouse vs Data Lake
  • SQL
    • SQL Basics
      • Creating and Modifying Tables/Views
      • Data Types
      • Joins
    • SQL Rules
    • SQL Aggregate Functions
    • SQL Window Functions
    • SQL Data Manipulation
      • String Operations
      • Date/Time Operations
    • SQL Descriptive Stats
    • SQL Tips
    • SQL Performance Tuning
    • SQL Customization
    • SQL Practice
      • Designing Databases
        • Spotify Database Design
      • Most Commonly Asked
      • Mixed Queries
      • Popular Websites For SQL Practice
        • SQLZoo
          • World - BBC Tables
            • SUM and COUNT Tutorial
            • SELECT within SELECT Tutorial
            • SELECT from WORLD Tutorial
            • Select Quiz
            • BBC QUIZ
            • Nested SELECT Quiz
            • SUM and COUNT Quiz
          • Nobel Table
            • SELECT from Nobel Tutorial
            • Nobel Quiz
          • Soccer / Football Tables
            • JOIN Tutorial
            • JOIN Quiz
          • Movie / Actor / Casting Tables
            • More JOIN Operations Tutorial
            • JOIN Quiz 2
          • Teacher - Dept Tables
            • Using Null Quiz
          • Edinburgh Buses Table
            • Self join Quiz
        • HackerRank
          • SQL (Basic)
            • Select All
            • Select By ID
            • Japanese Cities' Attributes
            • Revising the Select Query I
            • Revising the Select Query II
            • Revising Aggregations - The Count Function
            • Revising Aggregations - The Sum Function
            • Revising Aggregations - Averages
            • Average Population
            • Japan Population
            • Population Density Difference
            • Population Census
            • African Cities
            • Average Population of Each Continent
            • Weather Observation Station 1
            • Weather Observation Station 2
            • Weather Observation Station 3
            • Weather Observation Station 4
            • Weather Observation Station 6
            • Weather Observation Station 7
            • Weather Observation Station 8
            • Weather Observation Station 9
            • Weather Observation Station 10
            • Weather Observation Station 11
            • Weather Observation Station 12
            • Weather Observation Station 13
            • Weather Observation Station 14
            • Weather Observation Station 15
            • Weather Observation Station 16
            • Weather Observation Station 17
            • Weather Observation Station 18
            • Weather Observation Station 19
            • Higher Than 75 Marks
            • Employee Names
            • Employee Salaries
            • The Blunder
            • Top Earners
            • Type of Triangle
            • The PADS
          • SQL (Intermediate)
            • Weather Observation Station 5
            • Weather Observation Station 20
            • New Companies
            • The Report
            • Top Competitors
            • Ollivander's Inventory
            • Challenges
            • Contest Leaderboard
            • SQL Project Planning
            • Placements
            • Symmetric Pairs
            • Binary Tree Nodes
            • Interviews
            • Occupations
          • SQL (Advanced)
            • Draw The Triangle 1
            • Draw The Triangle 2
            • Print Prime Numbers
            • 15 Days of Learning SQL
          • TABLES
            • City - Country
            • Station
            • Hackers - Submissions
            • Students
            • Employee - Employees
            • Occupations
            • Triangles
        • StrataScratch
          • Netflix
            • Oscar Nominees Table
            • Nominee Filmography Table
            • Nominee Information Table
          • Audible
            • Easy - Audible
          • Spotify
            • Worldwide Daily Song Ranking Table
            • Billboard Top 100 Year End Table
            • Daily Rankings 2017 US
          • Google
            • Easy - Google
            • Medium - Google
            • Hard - Google
        • LeetCode
          • Easy
  • Python
    • Basics
      • Variables and DataTypes
        • Lists
        • Dictionaries
      • Control Flow
      • Functions
    • Object Oriented Programming
      • Restaurant Modeler
    • Pythonic Resources
    • Projects
  • Machine Learning
    • Fundamentals
      • Supervised Learning
        • Classification Algorithms
          • k-Nearest Neighbors
            • kNN Parameters & Attributes
          • Logistic Regression
        • Classification Report
      • UnSupervised Learning
        • Clustering
          • Evaluation
      • Preprocessing
        • Scalers: Standard vs MinMax
        • Feature Selection vs Dimensionality Reduction
        • Encoding
    • Frameworks
    • Machine Learning in Advertising
    • Natural Language Processing
      • Stopwords
      • Name Entity Recognition (NER)
      • Sentiment Analysis
        • Agoda Reviews - Part I - Scraping Reviews, Detecting Languages, and Preprocessing
        • Agoda Reviews - Part II - Sentiment Analysis and WordClouds
    • Recommendation Systems
      • Spotify Recommender System - Artists
  • Geospatial Analysis
    • Geospatial Analysis Basics
    • GSA at Work
      • Web Scraping and Mapping
  • GIT
    • GIT Essentials
    • Connecting to GitHub
  • FAQ
    • Statistics
  • Cloud Computing
    • Introduction to Cloud Computing
    • Google Cloud Platform
  • Docker
    • What is Docker?
Powered by GitBook
On this page

Was this helpful?

  1. SQL
  2. SQL Practice
  3. Popular Websites For SQL Practice
  4. HackerRank
  5. SQL (Advanced)

Print Prime Numbers

Last updated 1 year ago

Was this helpful?

Write a query to print all prime numbers less than or equal to 1000. Print your result on a single line, and use the ampersand (&) character as your separator (instead of a space).

For example, the output for all prime numbers ≤ 10 would be:

2&3&5&7
-- 3 Methods
-- 1) MYSQL without a Procedure
WITH RECURSIVE t AS (
    SELECT 2 AS nums
    UNION
    SELECT nums + 1
    FROM t
    WHERE nums < 1000
)
SELECT GROUP_CONCAT(nums SEPARATOR '&')
FROM t
WHERE nums NOT IN (
    SELECT DISTINCT a.nums
    FROM t a
    JOIN t b
    ON b.nums <= FLOOR(SQRT(a.nums)) 
        AND a.nums % b.nums = 0
)

-- 2) MYSQL with a Procedure

DELIMITER //
CREATE PROCEDURE printprime(n INT)
BEGIN
    DECLARE iter INT DEFAULT 2;
    DECLARE last INT DEFAULT n;
    DECLARE traversal INT DEFAULT 0;
    DECLARE divisible_count INT DEFAULT 0;
    DECLARE chain TEXT DEFAULT '';
    
    WHILE iter <= last DO
        SET divisible_count = 0;
        SET traversal = 2;
        WHILE traversal <= FLOOR(SQRT(iter)) DO
            IF iter % traversal = 0 THEN
                SET divisible_count = 1;
            END IF;
            SET traversal = traversal + 1;
        END WHILE ;
        IF divisible_count = 0 THEN
            IF iter = 2 THEN
                SET chain = '2';
            ELSE 
                SET chain = CONCAT(chain, '&', iter);
            END IF;
        END IF;
        SET iter = iter + 1;
    END WHILE;
    SELECT chain;
END //
DELIMITER ;

CALL printprime(1000);


/* 3) MSSQL
Recall Prime condition: Can be devided by itself or 1, and 1 is NOT a prime number/smallest prime number is 2
1- create a table for prime numbers since there is no table to choose data from
2- populate the table with only prime numbers
    i. declare (define) variables for: 
        a. number (INT,)
        b. dividers (INT)
        c. prime check (BIT, i.e. 1 or 0)
    ii.numbers will start from 1000 (since it is the max number to be checked), divider will check up to the 'number' that is being checked minus 1, and we will assume all numbers are prime first. 
        a. nr (INT, ≤ 1000)
        b. dividers (INT, ≤ NR-1)
        c. prime (all 1 at first)
    iii. if the all the dividers for certain number yield a non-zero remainder, then that number  will be added to the table
        a. number % divider <> 0 -> still prime, add too prime table
*/

CREATE TABLE prime_numbers (numbers INT);
-- declare (define) variable
DECLARE @nr INT;
DECLARE @divider INT;
DECLARE @prime BIT;

-- the smallest prime number is 2
SELECT @nr = 2;

-- Loop Through All Numbers
WHILE @nr <= 1000
    BEGIN
    SELECT @divider = @nr - 1; -- dividers (INT, ≤ NR-1)
    SELECT @prime = 1; -- all numbers assumed to be prime at first
    -- Prime test
    WHILE @divider > 1
        BEGIN
        IF @nr % @divider = 0
            SELECT @prime = 0 -- not a prime
        SELECT @divider = @divider - 1  -- loop till
        END
    IF @prime = 1
        INSERT INTO prime_numbers (numbers) VALUES (@nr)
    SELECT @nr = @nr - 1 -- loop till
END

-- Print all prime numbers
SELECT STRING_AGG(numbers,'&') FROM prime_numbers

Question Link