Ternary number system or Base 3 numbers | C ++ program to convert decimal number to ternary number ; 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
#include <cstdio> NEW_LINE #include <iostream> NEW_LINE #include <math.h> NEW_LINE using namespace std ; void convertToTernary ( int N ) { if ( N == 0 ) return ; int x = N % 3 ; N /= 3 ; if ( x < 0 ) N += 1 ; convertToTernary ( N ) ; if ( x < 0 ) cout << x + ( 3 * -1 ) ; else cout << x ; } void convert ( int Decimal ) { cout << " Ternary ▁ number ▁ of ▁ " << Decimal << " ▁ is : ▁ " ; if ( Decimal != 0 ) { convertToTernary ( Decimal ) ; } else cout << "0" << endl ; } int main ( ) { int Decimal = 2747 ; convert ( Decimal ) ; return 0 ; }