Python,C,C++ and JAVA programs for CBSE, ISC, B.Tech and I.T Computer Science and MCA students

The Programming Project: August 2021

Thursday, August 5, 2021

ISC COMPUTER SCIENCE THEORY PAPER JAVA PROGRAMS - 2018 Question 7


Question 7.

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)         [10]

 

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 a 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.

 

JAVA CODE
import java.util.*;
public class ISC2018TheoryQ7 {
       public static void main(String[] args) {
       int nn;
       Scanner in = new Scanner(System.in);
       System.out.println("Enter a positive integer:");
       nn = in.nextInt();
       Perfect obj = new Perfect(nn);
       obj.check();
       in.close();
       }
}
class Perfect {
    public void check(){
        if(num == sumOfFactors(num))
            System.out.println(num+" is a perfect number.");
        else
        System.out.println(num+" is not a perfect number.");
    }
    private int sumOfFactorsint i){
        if(i==key)          
            return 0;
        else if(i%key == 0)
            return key++ + sumOfFactors(i);
        else{
                key++;
                return sumOfFactors(i);
            }
    }
    Perfect(int nn)  {
        this.num = nn;
        this.key=1;
    }
    private int num;
    private int key;
}