16
Disarium Number in Python
Disarium Number:
A Disarium number is one in which the sum of each digit raised to the power of its respective position equals the original number.
like 135 , 89 etc.
Example1:
Input:
number =135
Output:
135 is disarium number
Explanation:
Here 1^1 + 3^2 + 5^3 = 135 so it is disarium Number
Example2:
Input:
number =79
Output:
79 is not disarium number
Explanation:
Here 7^1 + 9^2 = 87 not equal to 79 so it is not disarium Number
Disarium Number in Python
Below are the ways to check Disarium number in python
Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.
Method #1: Using while loop
Algorithm:
- Scan the number and calculate the size of the number.
- Make a copy of the number so you can verify the outcome later.
- Make a result variable (with a value of 0) and an iterator ( set to the size of the number)
- Create a while loop to go digit by digit through the number.
- On each iteration, multiply the result by a digit raised to the power of the iterator value.
- On each traversal, increment the iterator.
- Compare the result value to a copy of the original number.
Below is the implementation:
# given number num = 135 # intialize result to zero(ans) ans = 0 # calculating the digits digits = len(str(num)) # copy the number in another variable(duplicate) dup_number = num while (dup_number != 0): # getting the last digit remainder = dup_number % 10 # multiply the result by a digit raised to the power of the iterator value. ans = ans + remainder**digits digits = digits - 1 dup_number = dup_number//10 # It is disarium number if it is equal to original number if(num == ans): print(num, "is disarium number") else: print(num, "is not disarium number")
Output:
135 is disarium number
Method #2: By converting the number to string and Traversing the string to extract the digits
Algorithm:
- Initialize a variable say ans to 0
- Using a new variable, we must convert the given number to a string.
- Take a temp count =1 and increase the count after each iteration.
- Iterate through the string, convert each character to an integer, multiply the ans by a digit raised to the power of the count.
- If the ans is equal to given number then it is disarium number
Below is the implementation:
# given number num = 135 # intialize result to zero(ans) ans = 0 # make a temp count to 1 count = 1 # converting given number to string numString = str(num) # Traverse through the string for char in numString: # Converting the character of string to integer # multiply the ans by a digit raised to the power of the iterator value. ans = ans+int(char)**count count = count+1 # It is disarium number if it is equal to original number if(num == ans): print(num, "is disarium number") else: print(num, "is not disarium number")
Output:
135 is disarium number
16