Page 372 - computer science (868) class 11
P. 372

Let us study simple recursive methods with related programs.

              12.3.1 Recursive Methods on Numbers

                Program 6     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:                           [ISC 2018]

                              Class name                       :  Perfect
                              Data members/Instance variables
                              num                              :  To store the number
                              Methods/Member functions
                              Perfect (int nn)                 :   Parameterised constructor to initialise 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.
                1       class Perfect

                2       {
                3           int num; // data members

                4           // parameterised constructor
                5           Perfect(int nn)
                6           {

                7               num = nn;

                8           }
                9           int sum_of_factors(int i)
                10          {

                11              if(i == num)    // base case
                12                  rreturn 0;

                13              else if(num%i == 0)   // recursive case if i is a factor of num
                14                  return i+sum_of_factors(i+1);

                15              else   // recursive case if i is not a factor of num
                16                  return sum_of_factors(i+1);








                370370  Touchpad Computer Science-XI
   367   368   369   370   371   372   373   374   375   376   377