You are given two numbers a and b (1 <= a,b <= 10^8 ) and n. The task is to find all numbers between a and b inclusively having exactly n distinct prime factors. The solution should be designed in a way that it efficiently handles multiple queries for different values of a and b like in Competitive Programming.
Examples:Â
Â
Input : a = 1, b = 10, n = 2 Output : 2 // Only 6 = 2*3 and 10 = 2*5 have exactly two // distinct prime factors Input : a = 1, b = 100, n = 3 Output: 8 // only 30 = 2*3*5, 42 = 2*3*7, 60 = 2*2*3*5, 66 = 2*3*11, // 70 = 2*5*7, 78 = 2*3*13, 84 = 2*2*3*7 and 90 = 2*3*3*5 // have exactly three distinct prime factors
Â
This problem is basically application of segmented sieve. As we know that all prime factors of a number are always less than or equal to square root of number i.e; sqrt(n). So we generate all prime numbers less than or equals to 10^8 and store them in an array. Now using this segmented sieve we check each number from a to b to have exactly n prime factors.Â
Â
C++
// C++ program to find numbers with exactly n distinct// prime factor numbers from a to b#include<bits/stdc++.h>using namespace std;Â
// Stores all primes less than and equals to sqrt(10^8) = 10000vector <int> primes;Â
// Generate all prime numbers less than or equals to sqrt(10^8)// = 10000 using sieve of sundaramvoid segmentedSieve(){Â Â Â Â int n = 10000; // Square root of 10^8Â
    // In general Sieve of Sundaram, produces primes smaller    // than (2*x + 2) for a number given number x.    // Since we want primes smaller than n=10^4, we reduce    // n to half    int nNew = (n-2)/2;Â
    // This array is used to separate numbers of the form    // i+j+2ij from others where 1 <= i <= j    bool marked[nNew + 1];Â
    // Initialize all elements as not marked    memset(marked, false, sizeof(marked));Â
    // Main logic of Sundaram. Mark all numbers of the    // form i + j + 2ij as true where 1 <= i <= j    for (int i=1; i<=nNew; i++)        for (int j=i; (i + j + 2*i*j) <= nNew; j++)            marked[i + j + 2*i*j] = true;Â
    // Since 2 is a prime number    primes.push_back(2);Â
    // Remaining primes are of the form 2*i + 1 such that    // marked[i] is false.    for (int i=1; i<=nNew; i++)        if (marked[i] == false)            primes.push_back(2*i+1);}Â
// Function to count all numbers from a to b having exactly// n prime factorsint Nfactors(int a, int b, int n){Â Â Â Â segmentedSieve();Â
    // result --> all numbers between a and b having    // exactly n prime factors    int result = 0;Â
    // check for each number    for (int i=a; i<=b; i++)    {        // tmp --> stores square root of current number because        //         all prime factors are always less than and        //         equal to square root of given number        // copy --> it holds the copy of current number        int tmp = sqrt(i), copy = i;Â
        // count --> it counts the number of distinct prime        // factors of number        int count = 0;Â
        // check divisibility of 'copy' with each prime less        // than 'tmp' and divide it until it is divisible by        // current prime factor        for (int j=0; primes[j]<=tmp; j++)        {            if (copy%primes[j]==0)            {                // increment count for distinct prime                count++;                while (copy%primes[j]==0)                    copy = copy/primes[j];            }        }Â
        // if number is completely divisible then at last        // 'copy' will be 1 else 'copy' will be prime, so        // increment count by one        if (copy != 1)            count++;Â
        // if number has exactly n distinct primes then        // increment result by one        if (count==n)            result++;    }    return result;}Â
// Driver program to run the caseint main(){Â Â Â Â int a = 1, b = 100, n = 3;Â Â Â Â cout << Nfactors(a, b, n);Â Â Â Â return 0;} |
Java
// Java program to find numbers with exactly n distinct// prime factor numbers from a to bimport java.util.*;Â
class GFG{Â Â Â Â Â // Stores all primes less than and // equals to sqrt(10^8) = 10000static ArrayList<Integer> primes = new ArrayList<Integer>();Â
// Generate all prime numbers less // than or equals to sqrt(10^8)// = 10000 using sieve of sundaramstatic void segmentedSieve(){Â Â Â Â int n = 10000; // Square root of 10^8Â
    // In general Sieve of Sundaram,     // produces primes smaller    // than (2*x + 2) for a number     // given number x. Since we want     // primes smaller than n=10^4,     // we reduce n to half    int nNew = (n - 2)/2;Â
    // This array is used to separate     // numbers of the form i+j+2ij     // from others where 1 <= i <= j    boolean[] marked=new boolean[nNew + 1];Â
    // Main logic of Sundaram. Mark all     // numbers of the form i + j + 2ij    // as true where 1 <= i <= j    for (int i = 1; i <= nNew; i++)        for (int j = i; (i + j + 2 * i * j) <= nNew; j++)            marked[i + j + 2 * i * j] = true;Â
    // Since 2 is a prime number    primes.add(2);Â
    // Remaining primes are of the form 2*i + 1 such that    // marked[i] is false.    for (int i = 1; i <= nNew; i++)        if (marked[i] == false)            primes.add(2 * i + 1);}Â
// Function to count all numbers from a to b having exactly// n prime factorsstatic int Nfactors(int a, int b, int n){Â Â Â Â segmentedSieve();Â
    // result --> all numbers between a and b having    // exactly n prime factors    int result = 0;Â
    // check for each number    for (int i = a; i <= b; i++)    {        // tmp --> stores square root of current number because        //    all prime factors are always less than and        //    equal to square root of given number        // copy --> it holds the copy of current number        int tmp = (int)Math.sqrt(i), copy = i;Â
        // count --> it counts the number of distinct prime        // factors of number        int count = 0;Â
        // check divisibility of 'copy' with each prime less        // than 'tmp' and divide it until it is divisible by        // current prime factor        for (int j = 0; primes.get(j) <= tmp; j++)        {            if (copy % primes.get(j) == 0)            {                // increment count for distinct prime                count++;                while (copy % primes.get(j) == 0)                    copy = copy/primes.get(j);            }        }Â
        // if number is completely divisible then at last        // 'copy' will be 1 else 'copy' will be prime, so        // increment count by one        if (copy != 1)            count++;Â
        // if number has exactly n distinct primes then        // increment result by one        if (count == n)            result++;    }    return result;}Â
// Driver codepublic static void main (String[] args) {Â Â Â Â int a = 1, b = 100, n = 3;Â Â Â Â System.out.println(Nfactors(a, b, n));}}Â
// This code is contributed by chandan_jnu |
Python3
# Python3 program to find numbers with # exactly n distinct prime factor numbers# from a to bimport mathÂ
# Stores all primes less than and # equals to sqrt(10^8) = 10000primes = [];Â
# Generate all prime numbers less than # or equals to sqrt(10^8) = 10000# using sieve of sundaramdef segmentedSieve():Â
    n = 10000; # Square root of 10^8Â
    # In general Sieve of Sundaram, produces    # primes smaller than (2*x + 2) for a     # given number x. Since we want primes     # smaller than n=10^4, we reduce n to half    nNew = int((n - 2) / 2);Â
    # This array is used to separate     # numbers of the form i+j+2ij    # from others where 1 <= i <= j    marked = [False] * (nNew + 1);Â
    # Main logic of Sundaram. Mark all     # numbers of the form i + j + 2ij     # as true where 1 <= i <= j    for i in range(1, nNew + 1):        j = i;        while ((i + j + 2 * i * j) <= nNew):            marked[i + j + 2 * i * j] = True;            j += 1;Â
    # Since 2 is a prime number    primes.append(2);Â
    # Remaining primes are of the     # form 2*i + 1 such that     # marked[i] is false.    for i in range(1, nNew + 1):        if (marked[i] == False):            primes.append(2 * i + 1);Â
# Function to count all numbers # from a to b having exactly n # prime factorsdef Nfactors(a, b, n):Â
    segmentedSieve();Â
    # result --> all numbers between     # a and b having exactly n prime    # factors    result = 0;Â
    # check for each number    for i in range(a, b + 1):Â
        # tmp --> stores square root of         # current number because all prime         # factors are always less than and        # equal to square root of given number        # copy --> it holds the copy of         #          current number        tmp = math.sqrt(i);        copy = i;Â
        # count --> it counts the number of         # distinct prime factors of number        count = 0;Â
        # check divisibility of 'copy' with         # each prime less than 'tmp' and         # divide it until it is divisible        # by current prime factor        j = 0;        while (primes[j] <= tmp):            if (copy % primes[j] == 0):                                 # increment count for                # distinct prime                count += 1;                while (copy % primes[j] == 0):                    copy = (copy // primes[j]);            j += 1;Â
        # if number is completely divisible        # then at last 'copy' will be 1 else         # 'copy' will be prime, so increment        # count by one        if (copy != 1):            count += 1;Â
        # if number has exactly n distinct         # primes then increment result by one        if (count == n):            result += 1;Â
    return result;Â
# Driver Codea = 1;b = 100;n = 3;print(Nfactors(a, b, n));Â
# This code is contributed# by chandan_jnu |
C#
// C# program to find numbers with exactly n// distinct prime factor numbers from a to busing System;using System.Collections;Â
class GFG{Â Â Â Â Â // Stores all primes less than and // equals to sqrt(10^8) = 10000static ArrayList primes = new ArrayList();Â
// Generate all prime numbers less // than or equals to sqrt(10^8)// = 10000 using sieve of sundaramstatic void segmentedSieve(){Â Â Â Â int n = 10000; // Square root of 10^8Â
    // In general Sieve of Sundaram, produces     // primes smaller than (2*x + 2) for a number     // given number x. Since we want primes     // smaller than n=10^4, we reduce n to half    int nNew = (n - 2) / 2;Â
    // This array is used to separate     // numbers of the form i+j+2ij     // from others where 1 <= i <= j    bool[] marked = new bool[nNew + 1];Â
    // Main logic of Sundaram. Mark all     // numbers of the form i + j + 2ij    // as true where 1 <= i <= j    for (int i = 1; i <= nNew; i++)        for (int j = i;             (i + j + 2 * i * j) <= nNew; j++)            marked[i + j + 2 * i * j] = true;Â
    // Since 2 is a prime number    primes.Add(2);Â
    // Remaining primes are of the form    // 2*i + 1 such that marked[i] is false.    for (int i = 1; i <= nNew; i++)        if (marked[i] == false)            primes.Add(2 * i + 1);}Â
// Function to count all numbers from // a to b having exactly n prime factorsstatic int Nfactors(int a, int b, int n){Â Â Â Â segmentedSieve();Â
    // result --> all numbers between a and b     // having exactly n prime factors    int result = 0;Â
    // check for each number    for (int i = a; i <= b; i++)    {        // tmp --> stores square root of current        // number because all prime factors are         // always less than and equal to square         // root of given number        // copy --> it holds the copy of current number        int tmp = (int)Math.Sqrt(i), copy = i;Â
        // count --> it counts the number of         // distinct prime factors of number        int count = 0;Â
        // check divisibility of 'copy' with each         // prime less than 'tmp' and divide it until         // it is divisible by current prime factor        for (int j = 0; (int)primes[j] <= tmp; j++)        {            if (copy % (int)primes[j] == 0)            {                // increment count for distinct prime                count++;                while (copy % (int)primes[j] == 0)                    copy = copy / (int)primes[j];            }        }Â
        // if number is completely divisible then         // at last 'copy' will be 1 else 'copy'         // will be prime, so increment count by one        if (copy != 1)            count++;Â
        // if number has exactly n distinct         // primes then increment result by one        if (count == n)            result++;    }    return result;}Â
// Driver codepublic static void Main() {Â Â Â Â int a = 1, b = 100, n = 3;Â Â Â Â Console.WriteLine(Nfactors(a, b, n));}}Â
// This code is contributed by mits |
PHP
<?php// PHP program to find numbers with exactly n // distinct prime factor numbers from a to bÂ
// Stores all primes less than and equals // to sqrt(10^8) = 10000$primes = array();Â
// Generate all prime numbers less than or // equals to sqrt(10^8) = 10000 using// sieve of sundaramfunction segmentedSieve(){Â Â Â Â global $primes;Â Â Â Â $n = 10000; // Square root of 10^8Â
    // In general Sieve of Sundaram, produces    // primes smaller than (2*x + 2) for a     // given number x. Since we want primes     // smaller than n=10^4, we reduce n to half    $nNew = (int)(($n-2)/2);Â
    // This array is used to separate numbers of     // the form i+j+2ij from others where 1 <= i <= j    $marked = array_fill(0, $nNew + 1, false);Â
    // Main logic of Sundaram. Mark all numbers of the    // form i + j + 2ij as true where 1 <= i <= j    for ($i = 1; $i <= $nNew; $i++)        for ($j = $i;             ($i + $j + 2 * $i * $j) <= $nNew; $j++)            $marked[$i + $j + 2 * $i * $j] = true;Â
    // Since 2 is a prime number    array_push($primes, 2);Â
    // Remaining primes are of the form 2*i + 1     // such that marked[i] is false.    for ($i = 1; $i <= $nNew; $i++)        if ($marked[$i] == false)            array_push($primes, 2 * $i + 1);}Â
// Function to count all numbers from a to b // having exactly n prime factorsfunction Nfactors($a, $b, $n){Â Â Â Â global $primes;Â Â Â Â segmentedSieve();Â
    // result --> all numbers between a and b     // having exactly n prime factors    $result = 0;Â
    // check for each number    for ($i = $a; $i <= $b; $i++)    {        // tmp --> stores square root of current         // number because all prime factors are         // always less than and equal to square        // root of given number        // copy --> it holds the copy of current number        $tmp = sqrt($i);        $copy = $i;Â
        // count --> it counts the number of         // distinct prime factors of number        $count = 0;Â
        // check divisibility of 'copy' with each         // prime less than 'tmp' and divide it until         // it is divisible by current prime factor        for ($j = 0; $primes[$j] <= $tmp; $j++)        {            if ($copy % $primes[$j] == 0)            {                // increment count for distinct prime                $count++;                while ($copy % $primes[$j] == 0)                    $copy = (int)($copy / $primes[$j]);            }        }Â
        // if number is completely divisible then         // at last 'copy' will be 1 else 'copy'         // will be prime, so increment count by one        if ($copy != 1)            $count++;Â
        // if number has exactly n distinct primes         // then increment result by one        if ($count == $n)            $result++;    }    return $result;}Â
// Driver Code$a = 1;$b = 100;$n = 3;print(Nfactors($a, $b, $n));Â
// This code is contributed by chandan_jnu?> |
Javascript
<script>Â
    // JavaScript program to find numbers with exactly n    // distinct prime factor numbers from a to b         // Stores all primes less than and     // equals to sqrt(10^8) = 10000    let primes = [];Â
    // Generate all prime numbers less     // than or equals to sqrt(10^8)    // = 10000 using sieve of sundaram    function segmentedSieve()    {        let n = 10000; // Square root of 10^8Â
        // In general Sieve of Sundaram, produces         // primes smaller than (2*x + 2) for a number         // given number x. Since we want primes         // smaller than n=10^4, we reduce n to half        let nNew = parseInt((n - 2) / 2, 10);Â
        // This array is used to separate         // numbers of the form i+j+2ij         // from others where 1 <= i <= j        let marked = new Array(nNew + 1);        marked.fill(false);Â
        // Main logic of Sundaram. Mark all         // numbers of the form i + j + 2ij        // as true where 1 <= i <= j        for (let i = 1; i <= nNew; i++)            for (let j = i;                 (i + j + 2 * i * j) <= nNew; j++)                marked[i + j + 2 * i * j] = true;Â
        // Since 2 is a prime number        primes.push(2);Â
        // Remaining primes are of the form        // 2*i + 1 such that marked[i] is false.        for (let i = 1; i <= nNew; i++)            if (marked[i] == false)                primes.push(2 * i + 1);    }Â
    // Function to count all numbers from     // a to b having exactly n prime factors    function Nfactors(a, b, n)    {        segmentedSieve();Â
        // result --> all numbers between a and b         // having exactly n prime factors        let result = 0;Â
        // check for each number        for (let i = a; i <= b; i++)        {            // tmp --> stores square root of current            // number because all prime factors are             // always less than and equal to square             // root of given number            // copy --> it holds the copy of current number            let tmp = parseInt(Math.sqrt(i), 10), copy = i;Â
            // count --> it counts the number of             // distinct prime factors of number            let count = 0;Â
            // check divisibility of 'copy' with each             // prime less than 'tmp' and divide it until             // it is divisible by current prime factor            for (let j = 0; primes[j] <= tmp; j++)            {                if (copy % primes[j] == 0)                {                    // increment count for distinct prime                    count++;                    while (copy % primes[j] == 0)                        copy = parseInt(copy / primes[j], 10);                }            }Â
            // if number is completely divisible then             // at last 'copy' will be 1 else 'copy'             // will be prime, so increment count by one            if (copy != 1)                count++;Â
            // if number has exactly n distinct             // primes then increment result by one            if (count == n)                result++;        }        return result;    }         let a = 1, b = 100, n = 3;    document.write(Nfactors(a, b, n));     </script> |
Output:Â Â
8
If you have another approach to solve this problem then please share in comments.
This article is contributed by Shashank Mishra ( Gullu ). If you like neveropen and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the neveropen main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

… [Trackback]
[…] Find More Info here on that Topic: geeksforgeeks.org/exactly-n-distinct-prime-factor-numbers-from-a-to-b/ […]
… [Trackback]
[…] Find More Information here to that Topic: geeksforgeeks.org/exactly-n-distinct-prime-factor-numbers-from-a-to-b/ […]
… [Trackback]
[…] Read More here on that Topic: geeksforgeeks.org/exactly-n-distinct-prime-factor-numbers-from-a-to-b/ […]
… [Trackback]
[…] Read More on that Topic: geeksforgeeks.org/exactly-n-distinct-prime-factor-numbers-from-a-to-b/ […]