Perfect Number Java Program ISC 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 the sum of the factors of the number excluding itself is equal to the original number.

Example:
6 = 1 + 2 + 3 = 6, 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(int) and displays the result with an appropriate message.

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

Program:

import java.io.*;
class Perfect{
    private int num;
    public Perfect(int n){
        num = n;
    }
    public int sumOfFactors(int i){
        if(i == 1)
            return 1 + sumOfFactors(i + 1);
        else if(i < num && num % i == 0)
            return i + sumOfFactors(i + 1);
        else if(i < num && num % i != 0)
            return 0 + sumOfFactors(i + 1);
        else
            return 0;
    }
    public void check(){
        if(num == sumOfFactors(1))
            System.out.println(num + " is Perfect.");
        else
            System.out.println(num + " is not Perfect.");
    }
    public static void main(String args[])
    throws IOException{
        InputStreamReader in = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(in);
        System.out.print("Number: ");
        int n = Integer.parseInt(br.readLine());
        Perfect obj = new Perfect(n);
        obj.check();
    }
}

2 thoughts on “Perfect Number Java Program ISC 2018 Theory

  1. Sir,a program is given which states that:
    Write a Program in Java to input a number and check whether it is a Unique Number or not.

    ( A Unique number is a positive integer (without leading zeros) with no duplicate digits. For example 7, 135, 214 , 5243 are all unique numbers whereas 33, 3121, 200 are not.)

Leave a Reply