Python program to print all Disarium numbers between 1 to 100

PythonServer Side ProgrammingProgramming

When it is required to print all the disarium numbers between 1 and 100, a simple loop can be run between 1 and 100 and the length of every number can be calculated, and the power of the position can be multipled with the number itself.

If they are equal, it is considered as a disarium number.

A Disarium number is the one where the sum of its digits to the power of their respective position is equal to the original number itself.

Below is a demonstration for the same −

Example

 Live Demo

def length_calculation(my_val):
   len_val = 0
   while(my_val != 0):
      len_val = len_val + 1
      my_val = my_val//10
   return len_val
def digit_sum(my_num):
   remaining = sum_val = 0
   len_fun = length_calculation(my_num)
   while(my_num > 0):
      remaining = my_num%10
      sum_val = sum_val + (remaining**len_fun)
      my_num = my_num//10
      len_fun = len_fun - 1
   return sum_val
ini_result = 0
print("The disarium numbers between 1 and 100 are : ")
for i in range(1, 101):
   ini_result = digit_sum(i)
   if(ini_result == i):
      print(i)

Output

The disarium numbers between 1 and 100 are :
1
2
3
4
5
6
7
8
9
89

Explanation

  • Two methods are defined, that are used to find the number of digits in the number, and to get the product of the digit multiplied with its position.
  • An initial result is assigned to 0.
  • A loop is iterated over numbers between 1 and 101, (excluding 101), and if the number is same as the product of the digits in the number and the position, it is considered as a disarium number.
  • This is displayed as output on the console.
raja
Published on 12-Mar-2021 16:38:15
Advertisements