Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python program to check if the given number is a Disarium Number
A Disarium Number is a number where the sum of its digits raised to the power of their respective positions equals the original number itself. For example, 175 is a Disarium number because 11 + 72 + 53 = 1 + 49 + 125 = 175.
Understanding Disarium Numbers
To check if a number is a Disarium number, we need to ?
- Extract each digit from the number
- Calculate the total number of digits
- Raise each digit to the power of its position (1-based indexing)
- Sum all the results and compare with the original number
Method 1: Using Helper Function
This approach uses a separate function to calculate the number of digits ?
def length_calculation(num_val):
length = 0
while(num_val != 0):
length = length + 1
num_val = num_val//10
return length
my_num = 175
remaining = sum_val = 0
len_val = length_calculation(my_num)
print("Original number:", my_num)
num_val = my_num
while(my_num > 0):
remaining = my_num % 10
sum_val = sum_val + int(remaining**len_val)
my_num = my_num // 10
len_val = len_val - 1
if(sum_val == num_val):
print(str(num_val) + " is a disarium number!")
else:
print(str(num_val) + " isn't a disarium number")
Original number: 175 175 is a disarium number!
Method 2: Using String Conversion
A simpler approach using string methods to extract digits ?
def is_disarium(number):
num_str = str(number)
total = 0
for i, digit in enumerate(num_str):
total += int(digit) ** (i + 1)
return total == number
# Test with different numbers
test_numbers = [175, 192, 518, 135]
for num in test_numbers:
if is_disarium(num):
print(f"{num} is a disarium number!")
else:
print(f"{num} is not a disarium number")
175 is a disarium number! 192 is not a disarium number 518 is a disarium number! 135 is a disarium number!
Step-by-Step Verification
Let's verify 175 step by step ?
number = 175
digits = [int(d) for d in str(number)]
print(f"Number: {number}")
print(f"Digits: {digits}")
total = 0
for i, digit in enumerate(digits, 1):
power_result = digit ** i
total += power_result
print(f"{digit}^{i} = {power_result}")
print(f"Sum: {total}")
print(f"Is Disarium: {total == number}")
Number: 175 Digits: [1, 7, 5] 1^1 = 1 7^2 = 49 5^3 = 125 Sum: 175 Is Disarium: True
Comparison of Methods
| Method | Approach | Readability | Performance |
|---|---|---|---|
| Helper Function | Mathematical operations | Moderate | Good |
| String Conversion | String manipulation | High | Moderate |
Conclusion
A Disarium number has the sum of its digits raised to their positional powers equal to the original number. The string conversion method is more readable, while the mathematical approach is slightly more efficient for large numbers.
Advertisements
