Perfect Cube | Python3 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
import math NEW_LINE def insertPF ( primeFact , fact ) : NEW_LINE INDENT if ( fact in primeFact ) : NEW_LINE INDENT primeFact [ fact ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT primeFact [ fact ] = 1 NEW_LINE DEDENT return primeFact NEW_LINE DEDENT def primeFactors ( n ) : NEW_LINE INDENT primeFact = { } NEW_LINE while ( n % 2 == 0 ) : NEW_LINE INDENT primeFact = insertPF ( primeFact , 2 ) NEW_LINE n = n // 2 NEW_LINE DEDENT for i in range ( 3 , int ( math . sqrt ( n ) ) + 1 , 2 ) : NEW_LINE INDENT while ( n % i == 0 ) : NEW_LINE INDENT primeFact = insertPF ( primeFact , i ) NEW_LINE n = n // i NEW_LINE DEDENT DEDENT if ( n > 2 ) : NEW_LINE INDENT primeFact = insertPF ( primeFact , n ) NEW_LINE DEDENT return primeFact NEW_LINE DEDENT def perfectCube ( n ) : NEW_LINE INDENT primeFact = { } NEW_LINE primeFact = primeFactors ( n ) NEW_LINE for x in primeFact : NEW_LINE INDENT if ( primeFact [ x ] % 3 != 0 ) : NEW_LINE INDENT return " No " NEW_LINE DEDENT DEDENT return " Yes " NEW_LINE DEDENT N = 216 NEW_LINE print ( perfectCube ( N ) ) NEW_LINE