‹ Back to the paper
Design a class Pronic to check if a given number is a pronic number or not. [ A number is said to…
Design a class Pronic to check if a given number is a pronic number or not. [ A number is said to be pronic if the product of two consecutive numbers is equal to the number]
Example: 0 = 0 × 1
2 = 1 × 2
6 = 2 × 3
12 = 3 × 4
thus, 0, 2, 6, 12... are pronic numbers.
Some of the members of the class are given below:
Class name : Pronic
Data members/instance variables:
num : to store a positive integer number
Methods / Member functions:
Pronic( ) : default constructor to initialize the data member with legal initial value
void acceptnum( ) : to accept a positive integer number
boolean ispronic(int v) : returns true if the number ‘num’ is a pronic number, otherwise returns false using recursive technique
void check( ) : checks whether the given number is a pronic number by invoking the function ispronic() and displays the result with an appropriate message
Specify the class Pronic giving details of the constructor( ), void acceptnum( ), boolean ispronic(int) and void check( ). Define a main( ) function to create an object and call the functions accordingly to enable the task.
Answer
Answer
AIimport java.util.Scanner;
class Pronic
{
int num;
Pronic()
{
num = 0;
}
void acceptnum()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
num = sc.nextInt();
}
boolean ispronic(int v)
{
return ispronic(v, 0);
}
boolean ispronic(int v, int n)
{
if (n > v)
return false;
else if (n * (n + 1) == v)
return true;
else
return ispronic(v, n + 1);
}
void check()
{
if (ispronic(num))
System.out.println(num + " is a Pronic number.");
else
System.out.println(num + " is not a Pronic number.");
}
public static void main(String args[])
{
Pronic obj = new Pronic();
obj.acceptnum();
obj.check();
}
}Explanation: ispronic(int) is the required single-argument method from the specification; it forwards to an overloaded recursive helper ispronic(v, n) which tries successive values of n starting at 0 - a pronic number satisfies num = n*(n+1) for some non-negative integer n. If n*(n+1) exceeds v (n>v) without a match, it returns false; if n*(n+1)==v it returns true; otherwise it recurses with n+1. Tested (run for real): num=12 correctly reported "12 is a Pronic number." (since 3*4=12) and num=15 correctly reported "15 is not a Pronic number."From ISC 2023 Specimen Computer Science Paper 1, question 6.