Perfect Cube | C # 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
using System ; using System . Collections . Generic ; public class GFG { public static Dictionary < int , int > insertPF ( Dictionary < int , int > primeFact , int fact ) { if ( primeFact . ContainsKey ( fact ) ) { int freq ; freq = primeFact [ fact ] ; primeFact [ fact ] = ++ freq ; } else { primeFact . Add ( fact , 1 ) ; } return primeFact ; } public static Dictionary < int , int > primeFactors ( int n ) { Dictionary < int , int > primeFact = new Dictionary < int , int > ( ) ; 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 ) { Dictionary < int , int > primeFact ; primeFact = primeFactors ( n ) ; foreach ( int freq in primeFact . Values ) { if ( freq % 3 != 0 ) return " No " ; } return " Yes " ; } public static void Main ( String [ ] args ) { int N = 216 ; Console . WriteLine ( perfectCube ( N ) ) ; } }