Check if Decimal representation of an Octal number is divisible by 7 in Python

We need to check whether the decimal representation of a given octal number is divisible by 7. An octal number uses base 8, so we convert it to decimal and then check divisibility.

For example, if the octal number is 61, its decimal representation is 6×8¹ + 1×8? = 48 + 1 = 49, which is divisible by 7.

Algorithm

To solve this problem, we follow these steps ?

  • Initialize sum = 0
  • While the octal number is non-zero:
    • Add the last digit to sum
    • Remove the last digit from the number
  • If sum mod 7 equals 0, return True
  • Otherwise, return False

Method 1: Using Digit Extraction

We extract each digit of the octal number and sum them up ?

def solve(num):
    total = 0
    while num:
        total += num % 10
        num = num // 10
    if total % 7 == 0:
        return True
    return False

# Test with octal number 61
octal_num = 61
result = solve(octal_num)
print(f"Octal {octal_num} ? Decimal sum divisible by 7: {result}")

# Verify: 61 in octal = 6*8 + 1 = 49 in decimal
decimal_value = 6*8 + 1
print(f"Decimal value: {decimal_value}")
print(f"49 % 7 = {decimal_value % 7}")
Octal 61 ? Decimal sum divisible by 7: True
Decimal value: 49
49 % 7 = 0

Method 2: Using Built-in Conversion

We can also convert the octal string directly to decimal and check divisibility ?

def check_octal_divisible_by_7(octal_str):
    decimal_value = int(octal_str, 8)  # Convert octal to decimal
    return decimal_value % 7 == 0

# Test examples
test_cases = ['61', '70', '15', '21']

for octal in test_cases:
    decimal = int(octal, 8)
    is_divisible = check_octal_divisible_by_7(octal)
    print(f"Octal {octal} = Decimal {decimal}, Divisible by 7: {is_divisible}")
Octal 61 = Decimal 49, Divisible by 7: True
Octal 70 = Decimal 56, Divisible by 7: True
Octal 15 = Decimal 13, Divisible by 7: False
Octal 21 = Decimal 17, Divisible by 7: False

Comparison

Method Approach Best For
Digit Extraction Manual digit processing Understanding the algorithm
Built-in Conversion Direct base conversion Production code

Conclusion

Both methods effectively check if an octal number's decimal representation is divisible by 7. The built-in conversion method is more straightforward and less error-prone for practical applications.

Updated on: 2026-03-25T14:25:53+05:30

253 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements