Perfect Number ISC Computer Science 2018 Theory

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 n): parameterized constructor to initialize the data member num = n
int sumOfFactors(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 sumOfFactors() and displays the result with an appropriate message

Specify the class Perfect giving details of the constructor, int sumOfFactors(int) and void check(). Define a main() function to create an object and call the functions accordingly to enable the task.

import java.util.Scanner;
class Perfect{
    private int num;
    public Perfect(int n){
        num = Math.abs(n);
    }
    public int sumOfFactors(int i){
        if(num <= 1)
            return -1;
        if(i == num)
            return sumOfFactors(i - 1);
        else if(i == 1)
            return 1;
        else if(num % i == 0)
            return i + sumOfFactors(i - 1);
        else
            return sumOfFactors(i - 1);
    }
    public void check(){
        if(num == sumOfFactors(num))
            System.out.println("Perfect number!");
        else
            System.out.println("Not a Perfect number.");
    }
    public static void main(String args[]){
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the number: ");
        int n = Integer.parseInt(in.nextLine());
        Perfect obj = new Perfect(n);
        obj.check();
    }
}

Comments

Popular posts from this blog

Encrypt Program ISC Specimen 2023 Theory

No Repeat Program ISC Computer Science 2022 Semester 2 Theory

Bank Inheritance Program ISC Specimen 2023 Theory