A trendy number is defined as a three-digit number where the middle digit is divisible by 3. In this blog post, we’ll write a Python program to determine whether a given number is a trendy number or not.
Problem Description
Given an integer n
, the program should:
- Check if
n
is a three-digit number. - Verify if the middle digit of
n
is divisible by 3. - Output “Trendy Number” if both conditions are met; otherwise, output “Not a Trendy Number.”
Approach
- Check Number of Digits: Convert the number to a string to check if it has exactly three digits.
- Middle Digit Extraction: The middle digit can be accessed using string indexing.
- Divisibility Check: Convert the middle digit back to an integer and check if it’s divisible by 3.
- Print Result: Based on the checks, print the appropriate message.
Python Implementation
def is_trendy_number(n):
n_str = str(n)
# Check if the number has exactly 3 digits
if len(n_str) == 3:
middle_digit = int(n_str[1])
# Check if the middle digit is divisible by 3
if middle_digit % 3 == 0:
print("Trendy Number")
else:
print("Not a Trendy Number")
else:
print("Not a Trendy Number")
# Input Handling
n = int(input())
# Check if the number is a trendy number
is_trendy_number(n)
Explanation
- String Conversion: The number is converted to a string to easily access and check the number of digits and the middle digit.
- Middle Digit Check: The middle digit is accessed using
n_str[1]
and checked for divisibility by 3. - Conditional Output: If the conditions for a trendy number are met, “Trendy Number” is printed; otherwise, “Not a Trendy Number” is printed.
Test Cases
Let’s validate the program with some sample inputs:
# Test Case 1
# Input: 791
# Expected Output: Trendy Number
is_trendy_number(791)
# Test Case 2
# Input: 153
# Expected Output: Not a Trendy Number
is_trendy_number(153)
# Test Case 3
# Input: 945
# Expected Output: Trendy Number
is_trendy_number(945)
# Test Case 4
# Input: 29
# Expected Output: Not a Trendy Number
is_trendy_number(29)
# Test Case 5
# Input: 812
# Expected Output: Not a Trendy Number
is_trendy_number(812)
Conclusion
This simple program efficiently checks whether a given number is a trendy number by validating its digit length and checking the divisibility of the middle digit. It’s a straightforward approach suitable for beginners to understand basic string manipulation and conditional logic in Python. Try it out with different numbers to see if they are trendy or not!