3 Divisors Java

PROGRAM TO PRINT NUMBERS WITH EXACTLY THREE DIVISORS


import java.io.*;
import java.util.*;
  
class MAIN
{
    // 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); 
    }
}

OUTPUT

Numbers with 3 divisors :
4 9 25 49 

CREDITS: https://www.geeksforgeeks.org/numbers-exactly-3-divisors/

Comments

Popular posts from this blog

Solve the Sudoku Python

Solve the Sudoku Java

Find Duplicates Java