PRASHNIKAप्रश्निका
Back to the paper

Design a class Perfect to check if a given number is a perfect number or not. [ A number is said to…

Computer Science201810 marksProgram
Design a class Perfect to check if a given number is a perfect number or not. [ A number is said to be perfect if sum of the factors of the number excluding itself is equal to the original number] Example : 6 = 1 + 2 + 3 (where 1, 2 and 3 are factors of 6, excluding itself) Some of the members of the class are given below: Class name : Perfect Data members/instance variables: num : to store the number Methods/Member functions: Perfect (int nn) : parameterized constructor to initialize the data member num=nn int sum_of_factors(int i) : returns the sum of the factors of the number(num), excluding itself, using recursive technique void check( ) : checks whether the given number is perfect by invoking the function sum_of_factors( ) and displays the result with an appropriate message Specify the class Perfect giving details of the constructor( ), int sum_of_factors(int) and void check( ). Define a main( ) function to create an object and call the functions accordingly to enable the task.

Answer

Answer

AI
import java.util.Scanner;

class Perfect
{
    int num;

    Perfect(int nn)
    {
        num = nn;
    }

    int sum_of_factors(int i)
    {
        if (i > num / 2)
            return 0;
        else if (num % i == 0)
            return i + sum_of_factors(i + 1);
        else
            return sum_of_factors(i + 1);
    }

    void check()
    {
        int s = sum_of_factors(1);
        if (s == num)
            System.out.println(num + " is a Perfect number.");
        else
            System.out.println(num + " is not a Perfect number.");
    }

    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int nn = sc.nextInt();
        Perfect ob = new Perfect(nn);
        ob.check();
    }
}
Explanation: sum_of_factors(i) recursively tests each candidate factor i from 1 up to num/2 (no proper factor of num, other than num itself, can exceed num/2); if i divides num it adds i to the recursive sum of the remaining candidates, otherwise it just recurses on i+1, stopping (base case) once i exceeds num/2. check() compares this sum to num and prints the appropriate message. Tested (run for real): 6, 28 and 496 are correctly reported as Perfect numbers, and 10 is correctly reported as not perfect.
Objects

From ISC 2018 Computer Science Paper 1, question 7.