Skip to content
Related Articles

Related Articles

Improve Article

Queries to find whether a number has exactly four distinct factors or not

  • Difficulty Level : Easy
  • Last Updated : 06 Jul, 2021

Given a positive integers ‘q’ and ‘n’. For each query ‘q’ find whether a number ‘n’ have exactly four distinct divisors or not. If the number have exactly four divisors then print ‘Yes’ else ‘No’.1 <= q, n <= 106 
 

Input:
2
10
12
Output:
Yes
No

Explanation:
For 1st query, n = 10 has exactly four divisor i.e., 1, 2, 5, 10.
For 2nd query, n = 12 has exactly six divisor i.e., 1, 2, 3, 4, 6, 12.

 

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

Simple approach is to count factors by generating all divisors of a number by using this approach, after that check whether the count of all factors are equal to ‘4’ or not. Time complexity of this approach is O(sqrt(n)). 
Better approach is to use Number theory. For a number to be have four factors, it must satisfy the following conditions:- 
 

  1. If number is a product of exactly two prime numbers(say p, q). Thus we can assure that it will have four factors i.e, 1, p, q, n.
  2. If a number is cube of a prime number (or cube root of the number is prime). For example, let’s say n = 8, cube root = 2 that means ‘8’ can be written as 2*2*2 hence four factors are:- 1, 2, 4 and 8.

We can use sieve of Eratosthenes such that we will pre-calculate all the prime factor from 1 to 106. Now we will mark all numbers which are the product of two prime number by using two ‘for loops’ i.e, mark[p * q] =true. Meanwhile we will also mark all numbers(cube root) by taking cube of number i.e, mark[p * p * p] = true. 
After that we can easily answer each query in O(1) time. 
Below is pseudo code, have a look for better understanding 
 

C++




// C++ program to check whether number has
// exactly four distinct factors or not
#include <bits/stdc++.h>
using namespace std;
 
// Initialize global variable according
// to given condition so that it can be
// accessible to all function
const int N = 1e6;
bool fourDiv[N + 1];
 
// Function to calculate all number having
// four distinct distinct factors
void fourDistinctFactors()
{
    // Create a boolean array "prime[0..n]" and
    // initialize all entries it as true. A value
    // in prime[i] will finally be false if i is
    // not a prime, else true.
    bool primeAll[N + 1];
    memset(primeAll, true, sizeof(primeAll));
 
    for (int p = 2; p * p <= N; p++) {
 
        // If prime[p] is not changed, then it
        // is a prime
        if (primeAll[p] == true) {
 
            // Update all multiples of p
            for (int i = p * 2; i <= N; i += p)
                primeAll[i] = false;
        }
    }
 
    // Initialize prime[] array which will
    // contains all the primes from 1-N
    vector<int> prime;
 
    for (int p = 2; p <= N; p++)
        if (primeAll[p])
            prime.push_back(p);
 
    // Set the marking of all primes to false
    memset(fourDiv, false, sizeof(fourDiv));
 
    // Iterate over all the prime numbers
    for (int i = 0; i < prime.size(); ++i) {
        int p = prime[i];
 
        // Mark cube root of prime numbers
        if (1LL * p * p * p <= N)
            fourDiv[p * p * p] = true;
 
        for (int j = i + 1; j < prime.size(); ++j) {
            int q = prime[j];
 
            if (1LL * p * q > N)
                break;
 
            // Mark product of prime numbers
            fourDiv[p * q] = true;
        }
    }
}
 
// Driver program
int main()
{
    fourDistinctFactors();
 
    int num = 10;
    if (fourDiv[num])
        cout << "Yes\n";
    else
        cout << "No\n";
 
    num = 12;
    if (fourDiv[num])
        cout << "Yes\n";
    else
        cout << "No\n";
 
    return 0;
}

Java




// Java program to check whether number has
// exactly four distinct factors or not
import java.util.*;
class GFG{
// Initialize global variable according
// to given condition so that it can be
// accessible to all function
static int N = (int)1E6;
static boolean[] fourDiv=new boolean[N + 1];
 
// Function to calculate all number having
// four distinct distinct factors
static void fourDistinctFactors()
{
    // Create a boolean array "prime[0..n]" and
    // initialize all entries it as true. A value
    // in prime[i] will finally be false if i is
    // not a prime, else true.
    boolean[] primeAll=new boolean[N + 1];
 
    for (int p = 2; p * p <= N; p++) {
 
        // If prime[p] is not changed, then it
        // is a prime
        if (primeAll[p] == false) {
 
            // Update all multiples of p
            for (int i = p * 2; i <= N; i += p)
                primeAll[i] = true;
        }
    }
 
    // Initialize prime[] array which will
    // contains all the primes from 1-N
    ArrayList<Integer> prime=new ArrayList<Integer>();
 
    for (int p = 2; p <= N; p++)
        if (!primeAll[p])
            prime.add(p);
 
 
    // Iterate over all the prime numbers
    for (int i = 0; i < prime.size(); ++i) {
        int p = prime.get(i);
 
        // Mark cube root of prime numbers
        if (1L * p * p * p <= N)
            fourDiv[p * p * p] = true;
 
        for (int j = i + 1; j < prime.size(); ++j) {
            int q = prime.get(j);
 
            if (1L * p * q > N)
                break;
 
            // Mark product of prime numbers
            fourDiv[p * q] = true;
        }
    }
}
 
// Driver program
public static void main(String[] args)
{
    fourDistinctFactors();
 
    int num = 10;
    if (fourDiv[num])
        System.out.println("Yes");
    else
        System.out.println("No");
 
    num = 12;
    if (fourDiv[num])
        System.out.println("Yes");
    else
        System.out.println("No");
 
}
}
// This code is contributed by mits

Python3




# Python3 program to check whether number
# has exactly four distinct factors or not
 
# Initialize global variable according to
# given condition so that it can be
# accessible to all function
N = 1000001;
fourDiv = [False] * (N + 1);
 
# Function to calculate all number
# having four distinct factors
def fourDistinctFactors():
     
    # Create a boolean array "prime[0..n]"
    # and initialize all entries it as true.
    # A value in prime[i] will finally be
    # false if i is not a prime, else true.
    primeAll = [True] * (N + 1);
    p = 2;
 
    while (p * p <= N):
 
        # If prime[p] is not changed, then it
        # is a prime
        if (primeAll[p] == True):
 
            # Update all multiples of p
            i = p * 2;
            while (i <= N):
                primeAll[i] = False;
                i += p;
        p += 1;
 
    # Initialize prime[] array which will
    # contain all the primes from 1-N
    prime = [];
 
    for p in range(2, N + 1):
        if (primeAll[p]):
            prime.append(p);
 
    # Iterate over all the prime numbers
    for i in range(len(prime)):
        p = prime[i];
 
        # Mark cube root of prime numbers
        if (1 * p * p * p <= N):
            fourDiv[p * p * p] = True;
 
        for j in range(i + 1, len(prime)):
            q = prime[j];
 
            if (1 * p * q > N):
                break;
 
            # Mark product of prime numbers
            fourDiv[p * q] = True;
 
# Driver Code
fourDistinctFactors();
 
num = 10;
if (fourDiv[num]):
    print("Yes");
else:
    print("No");
 
num = 12;
if (fourDiv[num]):
    print("Yes");
else:
    print("No");
 
# This code is contributed by mits

C#




// C# program to check whether number has
// exactly four distinct factors or not
using System;
using System.Collections;
 
class GFG
{
     
// Initialize global variable according
// to given condition so that it can be
// accessible to all function
static int N = (int)1E6;
static bool[] fourDiv = new bool[N + 1];
 
// Function to calculate all number having
// four distinct distinct factors
static void fourDistinctFactors()
{
    // Create a boolean array "prime[0..n]" and
    // initialize all entries it as true. A value
    // in prime[i] will finally be false if i is
    // not a prime, else true.
    bool[] primeAll = new bool[N + 1];
 
    for (int p = 2; p * p <= N; p++)
    {
 
        // If prime[p] is not changed,
        // then it is a prime
        if (primeAll[p] == false)
        {
 
            // Update all multiples of p
            for (int i = p * 2; i <= N; i += p)
                primeAll[i] = true;
        }
    }
 
    // Initialize prime[] array which will
    // contains all the primes from 1-N
    ArrayList prime = new ArrayList();
 
    for (int p = 2; p <= N; p++)
        if (!primeAll[p])
            prime.Add(p);
 
    // Iterate over all the prime numbers
    for (int i = 0; i < prime.Count; ++i)
    {
        int p = (int)prime[i];
 
        // Mark cube root of prime numbers
        if (1L * p * p * p <= N)
            fourDiv[p * p * p] = true;
 
        for (int j = i + 1; j < prime.Count; ++j)
        {
            int q = (int)prime[j];
 
            if (1L * p * q > N)
                break;
 
            // Mark product of prime numbers
            fourDiv[p * q] = true;
        }
    }
}
 
// Driver Code
public static void Main()
{
    fourDistinctFactors();
 
    int num = 10;
    if (fourDiv[num])
        Console.WriteLine("Yes");
    else
        Console.WriteLine("No");
 
    num = 12;
    if (fourDiv[num])
        Console.WriteLine("Yes");
    else
        Console.WriteLine("No");
}
}
 
// This code is contributed by mits

PHP




<?php
// GFG PHP Compiler not support 64-bit
 
// PHP program to check whether
// number has exactly four
// distinct factors or not
 
// Initialize global variable
// according to given condition
// so that it can be accessible
// to all function
$N = 1000001;
$fourDiv = array_fill(0,
           $N + 1, false);
 
// Function to calculate
// all number having four
// distinct factors
function fourDistinctFactors()
{
    global $N;
    global $fourDiv;
     
    // Create a boolean array
    // "prime[0..n]" and initialize
    // all entries it as true. A
    // value in prime[i] will finally
    // be false if i is not a prime,
    // else true.
    $primeAll = array_fill(0, $N + 1, true);
 
    for ($p = 2;
         $p * $p <= $N; $p++)
    {
 
        // If prime[p] is not
        // changed, then it
        // is a prime
        if ($primeAll[$p] == true)
        {
 
            // Update all multiples of p
            for ($i = $p * 2;
                 $i <= $N; $i += $p)
                $primeAll[$i] = false;
        }
    }
 
    // Initialize prime[] array
    // which will contains all
    // the primes from 1-N
    $prime;
    $x = 0;
 
    for ($p = 2; $p <= $N; $p++)
        if ($primeAll[$p])
            $prime[$x++] = $p;
 
 
    // Iterate over all
    // the prime numbers
    for ($i = 0; $i < $x; ++$i)
    {
        $p = $prime[$i];
 
        // Mark cube root
        // of prime numbers
        if (1 * $p * $p * $p <= $N)
            $fourDiv[$p * $p * $p] = true;
 
        for ($j = $i + 1;
             $j < $x; ++$j)
        {
            $q = $prime[$j];
 
            if (1 * $p * $q > $N)
                break;
 
            // Mark product of
            // prime numbers
            $fourDiv[$p * $q] = true;
        }
    }
}
 
// Driver Code
fourDistinctFactors();
 
$num = 10;
if ($fourDiv[$num])
    echo "Yes\n";
else
    echo "No\n";
 
$num = 12;
if ($fourDiv[$num])
    echo "Yes\n";
else
    echo "No\n";
 
// This code is contributed by mits
?>

Javascript




<script>
 
// JavaScript program to check whether number has
// exactly four distinct factors or not
 
     
// Initialize global variable according
// to given condition so that it can be
// accessible to all function
var N = 1000000;
var fourDiv = Array(N+1).fill(false);
 
// Function to calculate all number having
// four distinct distinct factors
function fourDistinctFactors()
{
    // Create a boolean array "prime[0..n]" and
    // initialize all entries it as true. A value
    // in prime[i] will finally be false if i is
    // not a prime, else true.
    var primeAll = Array(N+1).fill(false);
 
    for (var p = 2; p * p <= N; p++)
    {
 
        // If prime[p] is not changed,
        // then it is a prime
        if (primeAll[p] == false)
        {
 
            // Update all multiples of p
            for (var i = p * 2; i <= N; i += p)
                primeAll[i] = true;
        }
    }
 
    // Initialize prime[] array which will
    // contains all the primes from 1-N
    var prime = [];
 
    for (var p = 2; p <= N; p++)
        if (!primeAll[p])
            prime.push(p);
 
    // Iterate over all the prime numbers
    for (var i = 0; i < prime.length; ++i)
    {
        var p = prime[i];
 
        // Mark cube root of prime numbers
        if (p * p * p <= N)
            fourDiv[p * p * p] = true;
 
        for(var j = i + 1; j < prime.length; ++j)
        {
            var q = prime[j];
 
            if (p * q > N)
                break;
 
            // Mark product of prime numbers
            fourDiv[p * q] = true;
        }
    }
}
 
// Driver Code
fourDistinctFactors();
var num = 10;
if (fourDiv[num])
    document.write("Yes<br>");
else
    document.write("No<br>");
num = 12;
if (fourDiv[num])
    document.write("Yes");
else
    document.write("No");
 
 
</script>

Output:  

Yes
No

Time complexity: O(1) for every query.
This article is contributed by Shubham Bansal. If you like GeeksforGeeks 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 GeeksforGeeks main page and help other Geeks.
 




My Personal Notes arrow_drop_up
Recommended Articles
Page :