Link to home
Start Free TrialLog in
Avatar of BehrangDBA
BehrangDBA

asked on

Writing a function to counts the number of primes in the range [1-N].

Hi everyone,
How can I  write a function that counts the number of primes in the range [1-N].
(A natural number is called a prime, a prime number or just prime if it has exactly two distinct divisors. Therefore, 1 is not prime number, since it has only one divisor, namely 1.)
Avatar of Pawan Kumar
Pawan Kumar
Flag of India image

Try this

--

DECLARE @StartRange AS INT = 2
DECLARE @EndRange AS INT = 50

SELECT COUNT (DISTINCT Number) PrimeNumbers
FROM
    MASTER..SPT_VALUES num
WHERE
    Number >= @StartRange AND Number <= @EndRange AND
        NOT EXISTS 
( 
        SELECT 1 FROM MASTER..SPT_VALUES AS num1 WHERE num1.Number > 1
    AND  num1.Number < num.Number
    AND  num.Number % num1.Number = 0
)

--

Open in new window


if you list of primes use below

--

DECLARE @StartRange AS INT = 2
DECLARE @EndRange AS INT = 50

SELECT DISTINCT Number PrimeNumbers
FROM
    MASTER..SPT_VALUES num
WHERE
    Number >= @StartRange AND Number <= @EndRange AND
        NOT EXISTS 
( 
        SELECT 1 FROM MASTER..SPT_VALUES AS num1 WHERE num1.Number > 1
    AND  num1.Number < num.Number
    AND  num.Number % num1.Number = 0
)

--

Open in new window


Output
------------------------
PrimeNumbers
-------------------------
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
ASKER CERTIFIED SOLUTION
Avatar of Pawan Kumar
Pawan Kumar
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi BehrangDBA,
Did you get a chance to check this?

Regards,
Pawan
Avatar of BehrangDBA
BehrangDBA

ASKER

Thank you very much for your time Pawan.