Numbers with exactly 3 divisors

Given a number N, print all numbers in the range from 1 to N having exactly 3 divisors. 
Examples: 

Input : N = 16
Output : 4 9
4 and 9 have exactly three divisors.
Divisor

Input : N = 49
Output : 4 9 25 49
4, 9, 25 and 49 have exactly three divisors.

After having a close look at the examples mentioned above, you have noticed that all the required numbers are perfect squares and that too are only of primes numbers. The logic behind this is, such numbers can have only three numbers as their divisor and also that includes 1 and that number itself resulting into just a single divisor other than a number, so we can easily conclude that required are those numbers which are squares of prime numbers so that they can have only three divisors (1, the number itself and sqrt(number)). So all primes i, such that i*i is less than equal to N are three-prime numbers. 
Note: We can generate all primes within a set using any sieve method efficiently and then we should all primes i, such that i*i <=N

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to print all
// three-primes smaller than
// or equal to n using Sieve
// of Eratosthenes
#include <bits/stdc++.h>
using namespace std;
 
// Generates all primes upto n and
// prints their squares
void numbersWith3Divisors(int n)
{
    bool prime[n+1];
    memset(prime, true, sizeof(prime));
    prime[0] = prime[1] = 0;
 
    for (int p = 2; p*p <= n; p++)
    {
        // If prime[p] is not changed,
        // then it is a prime
        if (prime[p] == true)
        {
           // Update all multiples of p
           for (int i = p*2; i <= n; i += p)
              prime[i] = false;
        }
    }
 
    // print squares of primes upto n.
    cout << "Numbers with 3 divisors :\n";
    for (int i=0;  i*i <= n ; i++)
        if (prime[i])
          cout << i*i << " ";
}
 
// Driver program
int main()
{
    // sieve();
    int n = 96;
    numbersWith3Divisors(n);
 
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to print all
// three-primes smaller than
// or equal to n using Sieve
// of Eratosthenes
import java.io.*;
import java.util.*;
 
class GFG
{
     
    // Generates all primes upto n
    // and prints their squares
    static void numbersWith3Divisors(int n)
    {
        boolean[] prime = new boolean[n+1];
        Arrays.fill(prime, true);
        prime[0] = prime[1] = false;
  
        for (int p = 2; p*p <= n; p++)
        {
             
            // If prime[p] is not changed,
            // then it is a prime
            if (prime[p] == true)
            {
                // Update all multiples of p
                for (int i=p*2; i<=n; i += p)
                    prime[i] = false;
            }
        }
  
        // print squares of primes upto n
        System.out.println("Numbers with 3 divisors : ");
        for (int i=0;  i*i <= n ; i++)
            if (prime[i])
                System.out.print(i*i + " ");
    }
     
    // Driver program
    public static void main (String[] args)
    {
        int n = 96;
        numbersWith3Divisors(n);
    }
}
 
// Contributed by Pramod Kumar

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to print
# all three-primes smaller than
# or equal to n using Sieve
# of Eratosthenes
 
# Generates all primes upto n
# and prints their squares
def numbersWith3Divisors(n):
  
    prime=[True]*(n+1);
    prime[0] = prime[1] = False;
    p=2;
    while (p*p <= n):
         
        # If prime[p] is not changed,
        # then it is a prime
        if (prime[p] == True):
             
            # Update all multiples of p
            for i in range(p*2,n+1,p):
                prime[i] = False;
        p+=1;
 
    # print squares of primes upto n.
    print("Numbers with 3 divisors :");
    i=0;
    while (i*i <= n):
        if (prime[i]):
            print(i*i,end=" ");
        i+=1;
 
# Driver program
 
n = 96;
numbersWith3Divisors(n);
 
# This code is contributed by mits

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to print all
// three-primes smaller than
// or equal to n using Sieve
// of Eratosthenes
 
class GFG
{
     
    // Generates all primes upto n
    // and prints their squares
    static void numbersWith3Divisors(int n)
    {
        bool[] prime = new bool[n+1];
        prime[0] = prime[1] = true;
 
        for (int p = 2; p*p <= n; p++)
        {
             
            // If prime[p] is not changed,
            // then it is a prime
            if (prime[p] == false)
            {
                // Update all multiples of p
                for (int i = p*2; i <= n; i += p)
                    prime[i] = true;
            }
        }
 
        // print squares of primes upto n
        System.Console.WriteLine("Numbers with 3
                                  divisors : ");
        for (int i=0; i*i <= n ; i++)
            if (!prime[i])
                System.Console.Write(i*i + " ");
    }
     
    // Driver program
    public static void Main()
    {
        int n = 96;
        numbersWith3Divisors(n);
    }
}
 
// This code is Contributed by mits

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to print all three-primes
// smaller than or equal to n using Sieve
// of Eratosthenes
 
// Generates all primes upto n and
// prints their squares
function numbersWith3Divisors($n)
{
    $prime = array_fill(0, $n + 1, true);
    $prime[0] = $prime[1] = false;
 
    for ($p = 2; $p * $p <= $n; $p++)
    {
        // If prime[p] is not changed,
        // then it is a prime
        if ($prime[$p] == true)
        {
        // Update all multiples of p
        for ($i = $p * 2; $i <= $n; $i += $p)
            $prime[$i] = false;
        }
    }
 
    // print squares of primes upto n.
    echo "Numbers with 3 divisors :\n";
    for ($i = 0; $i * $i <= $n ; $i++)
        if ($prime[$i])
        echo $i * $i . " ";
}
 
// Driver Code
$n = 96;
numbersWith3Divisors($n);
 
// This code is contributed by mits
?>

chevron_right


Output: 

Numbers with 3 divisors :
4 9 25 49 

Another Approach:



To print all numbers in the range from 1 to N having exactly 3 divisors, the main calculation is to find those which are squares of prime numbers and less than or equal to the number. We can do this as follows:

  1. Start a loop for integer i from 2 to n.
  2. Check if i is prime or not, which can be done easily using the isPrime(n) method.
  3. If i is prime, check if its square is less than or equal to the given number. This will be checked only for squares of prime numbers, therefore reducing the number of checks.
  4. If the above condition is satisfied, the number will be printed and the loop will continue till i<=n.

In this way, no extra space will be required to store anything.

Here is an implementation of the above logic without using extra space, in Java;

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to print all
// three-primes smaller than
// or equal to n without using
// extra space
#include <bits/stdc++.h>
using namespace std;
 
void numbersWith3Divisors(int);
bool isPrime(int);
 
// Generates all primes upto n and
// prints their squares
void numbersWith3Divisors(int n)
{
    cout << "Numbers with 3 divisors : "
         << endl;
 
    for(int i = 2; i * i <= n; i++)
    {
         
        // Check prime
        if (isPrime(i))
        {
            if (i * i <= n)
            {
                 
                // Print numbers in
                // the order of
                // occurence
                cout << i * i << " ";
            }
        }
    }
}
 
// Check if a number is prime or not
bool isPrime(int n)
{
    if (n == 0 || n == 1)
        return false;
         
    for(int i = 2; i * i <= n; i++)
    {
        if (n % i == 0)
            return false;
    }
    return true;
}
 
// Driver code
int main()
{
    int n = 122;
 
    numbersWith3Divisors(n);
 
    return 0;
}
 
// This code is contributed by vishu2908

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to print all
// three-primes smaller than
// or equal to n without using
// extra space
import java.util.*;
 
class GFG
{
 
    // 3 divisor logic implementation
    // check if a number is
    // prime or not
    // if it is a prime then
    // check if its square
    // is less than or equal to
    // the given number
    static void numbersWith3Divisors(int n)
    {
        System.out.println("Numbers with 3
                                divisors : ");
 
        for (int i = 2; i * i <= n; i++)
        {
             
            // Check prime
            if (isPrime(i))
            {
                if (i * i <= n)
                {
                     
                    // Print numbers in
                    // the order of
                    // occurence
                    System.out.print(i * i + " ");
                }
            }
        }
    }
                            
    // Check if a number is prime or not
    public static boolean isPrime(int n)
    {
        if (n == 0 || n == 1)
            return false;
        for (int i = 2; i * i <= n; i++)
        {
            if (n % i == 0)
                return false;
        }
        return true;
    }
 
    // Driver program
    public static void main(String[] args)
    {
        int n = 122;
        numbersWith3Divisors(n);
    }
}
 
// Contributed by Parag Pallav Singh

chevron_right


Output:

Numbers with 3 divisors :
4 9 25 49 121

This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks 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.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up