‹ Back to the paper
Design a class NumDude to check if a given number is a Dudeney number or not. (A Dudeney number is…
Design a class NumDude to check if a given number is a Dudeney number or not. (A Dudeney number is a positive integer that is a perfect cube, such that the sum of its digits is equal to the cube root of the number.)
Example: $5832 = (5+8+3+2)^3 = (18)^3 = 5832$
Some of the members of the class are given below:
Specify the class NumDude giving details of the constructor( ), void input( ), int sumDigits(int) and void isDude( ). Define a main( ) function to create an object and call the functions accordingly to enable the task.
| Class name | : | NumDude |
|---|---|---|
| **Data member/instance variable:** | ||
| num | : | to store a positive integer number |
| **Methods / Member functions:** | ||
| NumDude( ) | : | default constructor to initialise the data member with legal initial value |
| void input( ) | : | to accept a positive integer number |
| int sumDigits(int x) | : | returns the sum of the digits of number ‘x’ using recursive technique |
| void isDude( ) | : | checks whether the given number is a Dudeney number by invoking the function sumDigits() and displays the result with an appropriate message |
Answer
Answer
AIimport java.util.Scanner;
class NumDude
{
int num; // the number to be checked
// default constructor
NumDude()
{
num = 0;
}
// accepts a positive integer
void input()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
num = sc.nextInt();
}
// returns the sum of the digits of x using recursion
int sumDigits(int x)
{
if (x == 0)
return 0;
return (x % 10) + sumDigits(x / 10);
}
// checks whether num is a Dudeney number
void isDude()
{
int s = sumDigits(num);
if (s * s * s == num)
System.out.println(num + " is a Dudeney number");
else
System.out.println(num + " is not a Dudeney number");
}
public static void main(String args[])
{
NumDude ob = new NumDude();
ob.input();
ob.isDude();
}
}sumDigits() adds the last digit (x % 10) to the sum of the remaining digits (x / 10) until x becomes 0. isDude() cubes that sum: if the cube equals the number, the sum is its cube root, so the number is a Dudeney number.
Sample run:Enter a positive integer: 5832
5832 is a Dudeney numberFrom ISC 2023 Computer Science Paper 1, question 6.