Python Program to Convert Decimal to Octal Number
oct(decimal_number) which returns a string with prefix '0o', or by using a custom function that divides the number by 8 repeatedly and collects remainders.Examples
How to Think About It
oct() function can be used to get the octal representation directly.Algorithm
Code
def decimal_to_octal(num): if num == 0: return '0' octal = '' while num > 0: octal = str(num % 8) + octal num //= 8 return octal number = 65 print(f"Octal of {number} is {decimal_to_octal(number)}")
Dry Run
Let's trace the decimal number 65 through the code to convert it to octal.
Start with number 65
num = 65, octal = ''
Divide 65 by 8
65 % 8 = 1 (remainder), 65 // 8 = 8 (quotient), octal = '1'
Divide 8 by 8
8 % 8 = 0 (remainder), 8 // 8 = 1 (quotient), octal = '01'
Divide 1 by 8
1 % 8 = 1 (remainder), 1 // 8 = 0 (quotient), octal = '101'
Number is now 0, stop
Final octal string = '101'
| num before division | remainder (num % 8) | quotient (num // 8) | octal string |
|---|---|---|---|
| 65 | 1 | 8 | 1 |
| 8 | 0 | 1 | 01 |
| 1 | 1 | 0 | 101 |
Why This Works
Step 1: Using modulo to find remainder
Each time we divide the number by 8, the remainder gives the next octal digit from right to left.
Step 2: Building the octal string
We add each remainder to the front of the string to build the octal number in correct order.
Step 3: Stopping condition
When the number becomes zero after division, all octal digits have been found.
Alternative Approaches
number = 65 print(oct(number))
def decimal_to_octal_recursive(num): if num == 0: return '' return decimal_to_octal_recursive(num // 8) + str(num % 8) number = 65 result = decimal_to_octal_recursive(number) or '0' print(result)
Complexity: O(log n) time, O(log n) space
Time Complexity
The algorithm divides the number by 8 repeatedly, so the number of steps is proportional to the number of octal digits, which is logarithmic in base 8.
Space Complexity
The space used is for the output string storing octal digits, which grows with the number of digits, also logarithmic.
Which Approach is Fastest?
Using Python's built-in oct() is fastest and simplest, while manual methods offer learning value but are slower.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Built-in oct() | O(1) | O(1) | Quick and simple conversion |
| Iterative division | O(log n) | O(log n) | Learning and manual control |
| Recursive division | O(log n) | O(log n) | Understanding recursion |
oct() for quick conversion, but remove the '0o' prefix if you want only digits.