Perfect Cube | C ++ program to check if a number is a perfect cube using prime factors ; Inserts the prime factor in HashMap 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 perfect cube ; Iteration in Map ; Driver Code ; Function to check if N is perfect cube or not
#include <bits/stdc++.h> NEW_LINE using namespace std ; map < int , int > insertPF ( map < int , int > primeFact , int fact ) { if ( primeFact . find ( fact ) != primeFact . end ( ) ) { primeFact [ fact ] ++ ; } else { primeFact [ fact ] = 1 ; } return primeFact ; } map < int , int > primeFactors ( int n ) { map < int , int > primeFact ; while ( n % 2 == 0 ) { primeFact = insertPF ( primeFact , 2 ) ; n /= 2 ; } for ( int i = 3 ; i <= sqrt ( n ) ; i += 2 ) { while ( n % i == 0 ) { primeFact = insertPF ( primeFact , i ) ; n /= i ; } } if ( n > 2 ) primeFact = insertPF ( primeFact , n ) ; return primeFact ; } string perfectCube ( int n ) { map < int , int > primeFact ; primeFact = primeFactors ( n ) ; for ( auto x : primeFact ) { if ( x . second % 3 != 0 ) return " No " ; } return " Yes " ; } int main ( ) { int N = 216 ; cout << perfectCube ( N ) ; return 0 ; }