Perfect Cube | Java program to check if a number is a perfect cube using prime factors ; Inserts the prime factor in the Hash Map if not present If present updates it 's frequency ; A utility function to find all prime factors of a given number N ; Insert the number of 2 s that divide n ; n must be odd at this point . So we can skip one element ; While i divides n , insert i and divide n ; This condition is to handle the case when n is a prime number greater than 2 ; Function to check if a number is a perfect cube ; Using values ( ) for iteration over keys ; Driver Code ; Function to check if N is perfect cube or not
import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { public static HashMap < Integer , Integer > insertPF ( HashMap < Integer , Integer > primeFact , int fact ) { if ( primeFact . containsKey ( fact ) ) { int freq ; freq = primeFact . get ( fact ) ; primeFact . replace ( fact , ++ freq ) ; } else { primeFact . put ( fact , 1 ) ; } return primeFact ; } public static HashMap < Integer , Integer > primeFactors ( int n ) { HashMap < Integer , Integer > primeFact = new HashMap < > ( ) ; while ( n % 2 == 0 ) { primeFact = insertPF ( primeFact , 2 ) ; n /= 2 ; } for ( int i = 3 ; i <= Math . sqrt ( n ) ; i += 2 ) { while ( n % i == 0 ) { primeFact = insertPF ( primeFact , i ) ; n /= i ; } } if ( n > 2 ) primeFact = insertPF ( primeFact , n ) ; return primeFact ; } public static String perfectCube ( int n ) { HashMap < Integer , Integer > primeFact ; primeFact = primeFactors ( n ) ; for ( int freq : primeFact . values ( ) ) { if ( freq % 3 != 0 ) return " No " ; } return " Yes " ; } public static void main ( String [ ] args ) { int N = 216 ; System . out . println ( perfectCube ( N ) ) ; } }