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
function convertToTernary ( N ) { if ( N == 0 ) return ; let x = N % 3 ; N = parseInt ( N / 3 , 10 ) ; if ( x < 0 ) N += 1 ; convertToTernary ( N ) ; if ( x < 0 ) document . write ( x + ( 3 * - 1 ) ) ; else document . write ( x ) ; } function convert ( Decimal ) { document . write ( " " + Decimal + " " ) ; if ( Decimal != 0 ) { convertToTernary ( Decimal ) ; } else document . write ( " " + " " ) ; } let Decimal = 2747 ; convert ( Decimal ) ;