The program is written here to convert a binary number into its equivalent octal number.
The binary number is taken as input from the user. The decimal number can be calculated by adding the products of each digit and the power of 2 starting from 0 from the right to left.
For example, the binary number is 101101.
The decimal number will be:
= 32 + 0 + 8 + 4 + 0 + 1 = 45.
Now this decimal value will be converted to its equivalent octal by dividing the number with 8, again divide the quotient with 8 and so on until the number becomes 0. The remainder after each division will be shown in the reversed order. Hence, we will get the octal number. The example is given below:
Therefore, the equivalent octal number is ()
INPUT: A binary number
OUTPUT: Equivalent Octal Number
PROCESS:
Step 1: [Taking the input]
Read n [the binary number]
Step 2: [Converting from binary to octal]
Set d<-0
Set p<-0
[Converting from binary to decimal]
While n>0 repeat
[Calculating the power of 2 and multiplied with the binary digit]
Set d<-d+(n mod 10)×2p
[Increasing the power]
Set p<-p+1
Set n<-n/10
[End of ‘while’ loop]
[Converting from decimal to octal]
Set p<-1
While d>0 repeat
Set oct<-oct+(d mod 8)×p
Set d<-d/8
Set p<-p×10
[End of ‘while’ loop]
[Printing the octal number]
Print "The octal number is: oct”
Step 3: Stop.
while(n>0)-----------------------------------------O(k)
{
//calculating the power of 2 and multiplied
//with the binary digit
d=d+(n%10)*pow(2,p);
//increasing the power
p+=1;
n=n/10;
}
printf("\nThe decimal is: %d\n",p);
//converting from decimal to octal
p=1;
while(d>0)---------------------------------------O(m)
{
oct=oct+(d%8)*p;
d=d/8;
p=p*10;
}
The time complexity of this program is O (k+m) where ‘k’ is the number of digits of the binary number and ‘m’ is the number of digits of the decimal number.
The space complexity of this program is O (1) as it requires a constant number of memory spaces to execute the program for any given input.