Ternary number system or Base 3 numbers | Function to convert a decimal number to a ternary number ; Base case ; Finding the remainder when N is divided by 3 ; Recursive function to call the function for the integer division of the value N / 3 ; Handling the negative cases ; Function to convert the decimal to ternary ; If the number is greater than 0 , compute the ternary representation of the number ; Driver Code
def convertToTernary ( N ) : NEW_LINE INDENT if ( N == 0 ) : NEW_LINE INDENT return ; NEW_LINE DEDENT x = N % 3 ; NEW_LINE N //= 3 ; NEW_LINE if ( x < 0 ) : NEW_LINE INDENT N += 1 ; NEW_LINE DEDENT convertToTernary ( N ) ; NEW_LINE if ( x < 0 ) : NEW_LINE INDENT print ( x + ( 3 * - 1 ) , end = " " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( x , end = " " ) ; NEW_LINE DEDENT DEDENT def convert ( Decimal ) : NEW_LINE INDENT print ( " Ternary ▁ number ▁ of ▁ " , Decimal , " ▁ is : ▁ " , end = " " ) ; NEW_LINE if ( Decimal != 0 ) : NEW_LINE INDENT convertToTernary ( Decimal ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( "0" , end = " " ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT Decimal = 2747 ; NEW_LINE convert ( Decimal ) ; NEW_LINE DEDENT