Pankaj Gupta Scholar
Program to Check for A Disarium number
A Disarium number is a number where the sum of its digits powered with their respective positions is equal to the number itself. For example, 175 is a Disarium number because: . Here’s a simple Java program to check if a number is a Disarium number:
import java.util.Scanner;
public class DisariumNumber
{ // Method to calculate the number of digits in a number
public static int countDigits(int number)
{ int count = 0;
while (number != 0)
{ count++;
number /= 10;
}
return count;
}
// Method to check if the number is Disarium
public static boolean isDisarium(int number)
{ int sum = 0, temp = number;
int digits = countDigits(number);
// Calculate sum of digits powered by their respective positions
while (temp != 0)
{ int digit = temp % 10;
sum += Math.pow(digit, digits--);
temp /= 10;
}
// Return true if sum equals the original number
return sum == number;
}
public static void main(String[] args)
{ Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
if (isDisarium(number))
{ System.out.println(number + " is a Disarium number."); }
else
{ System.out.println(number + " is not a Disarium number."); }
scanner.close();
}
}
How the program works
- The
countDigits
method counts how many digits are in the number. - The
isDisarium
method calculates the sum of each digit raised to the power of its position (starting from 1). - The
main
method prompts the user for a number, checks if it’s a Disarium number, and outputs the result.