From ff82b595e087f194bda62ef948998e26ff0aaca4 Mon Sep 17 00:00:00 2001 From: Shreyansh Jain Date: Tue, 24 Nov 2026 16:06:05 +0530 Subject: [PATCH] fix(conversions): use integer arithmetic in decimal_to_octal decimal_to_octal built its result with floating-point helpers: math.pow(10, counter) for the digit position and math.floor(num / 8) for the division. Both lose precision once the values leave the exact-integer range of a double. The smallest input that came out wrong is 2**53 + 7, where the conversion of num to a double rounds up and the quotient chain gains a digit; math.pow also goes inexact from 10**23 and raises OverflowError past 10**308. Use 10**counter and num //= 8 instead, which keeps everything in Python's arbitrary-precision integers and drops the math import, and extend the doctests to cover the three inputs that previously failed. --- conversions/decimal_to_octal.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/conversions/decimal_to_octal.py b/conversions/decimal_to_octal.py index 4c313bddf64c..d8cbce1e6649 100644 --- a/conversions/decimal_to_octal.py +++ b/conversions/decimal_to_octal.py @@ -1,7 +1,5 @@ """Convert a Decimal Number to an Octal Number.""" -import math - # Modified from: # https://github.com/TheAlgorithms/Javascript/blob/master/Conversions/DecimalToOctal.js @@ -12,16 +10,21 @@ def decimal_to_octal(num: int) -> str: >>> all(decimal_to_octal(i) == oct(i) for i ... in (0, 2, 8, 64, 65, 216, 255, 256, 512)) True + >>> decimal_to_octal(2**53 + 7) + '0o400000000000000007' + >>> decimal_to_octal(8**23) == oct(8**23) + True + >>> decimal_to_octal(8**309) == oct(8**309) + True """ octal = 0 counter = 0 while num > 0: remainder = num % 8 - octal = octal + (remainder * math.floor(math.pow(10, counter))) + octal = octal + (remainder * 10**counter) counter += 1 - num = math.floor(num / 8) # basically /= 8 without remainder if any - # This formatting removes trailing '.0' from `octal`. - return f"0o{int(octal)}" + num //= 8 + return f"0o{octal}" def main() -> None: