‹ Back to the paper
Design a class ArmNum to check if a given number is an Armstrong number or not. [A number is said…
Design a class ArmNum to check if a given number is an Armstrong number or not.
[A number is said to be Armstrong if sum of its digits raised to the power of length of the number is equal to the number]
Example : 371 = $3^3 + 7^3 + 1^3$
1634 = $1^4 + 6^4 + 3^4 + 4^4$
54748 = $5^5 + 4^5 + 7^5 + 4^5 + 8^5$
Thus 371, 1634 and 54748 are all examples of Armstrong numbers.
Some of the members of the class are given below:
Class name : ArmNum
Data members/instance variables:
n : to store the number
l : to store the length of the number
Methods/Member functions:
ArmNum (int nn) : parameterized constructor to initialize the data member n=nn
int sum_pow(int i) : returns the sum of each digit raised to the power of the length of the number using recursive technique
eg. 34 will return $3^2 + 4^2$ (as the length of the number is 2)
void isArmstrong( ) : checks whether the given number is an Armstrong number by invoking the function sum_pow( ) and displays the result with an appropriate message
Specify the class ArmNum giving details of the constructor( ), int sum_pow(int) and void isArmstrong( ). Define a main( ) function to create an object and call the functions accordingly to enable the task.
Answer
Answer
AIimport java.util.Scanner;
class ArmNum
{
int n;
int l;
ArmNum(int nn)
{
n = nn;
l = String.valueOf(n).length();
}
int sum_pow(int i)
{
if (i == 0)
return 0;
else
{
int digit = i % 10;
return (int) Math.pow(digit, l) + sum_pow(i / 10);
}
}
void isArmstrong()
{
int s = sum_pow(n);
if (s == n)
System.out.println(n + " is an Armstrong number.");
else
System.out.println(n + " is not an Armstrong number.");
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int nn = sc.nextInt();
ArmNum obj = new ArmNum(nn);
obj.isArmstrong();
}
}Explanation: the constructor stores the number n and its length l (number of digits, found via String.valueOf(n).length()). sum_pow(i) recursively strips the last digit of i at each call (i%10), raises it to the power l (the length of the original number, a fixed value throughout the recursion), and adds it to the recursive call on the remaining digits (i/10), stopping when i becomes 0. isArmstrong() compares this sum to n and prints the appropriate message. Tested (run for real): for n=371, sum_pow computes 3^3+7^3+1^3=371 and the program correctly printed "371 is an Armstrong number."From ISC 2019 Computer Science Paper 1, question 7.