Hello everyone, i need help with using recursion in writing quite a simple code, but i'm kind of lost with recursion. The assignment is:
When the user enters a certain amount of whole positive numbers and presses enter, the main function calls to the recursive separate functions that do the following
1. count the number of digits in each number
2. count the sum of the digits
3. finds out what the largest digit is.
4. What confuses me the most - figures out the divisors and the factors, which are prime numbers divisors. For example - for 84 it would print 2, 2, 3, 7
5. figures out if the input number is a prime one

It's all easy when done by loops, but i'm very confused when it comes to converting it into recursion. I would be greatful for any ideas for code and use of recursion in case like that. Thank you.

OK, from what i understand, you basically need 5 recursive functions:

1) This returns the count.

    if (num equals 0) 
         return 0;
    return 1 + compute_digits_count(num / 10)

The above code finds the number of digits. For the sum, this hint would be enough:
Hint: Digits can be obtained using the '%' operator.

3) This returns the maximum digit.

max = 0;

    if (num equals 0) 
         return max;
    if (num % 10 > max)
 	max = num % 10;
    compute_digits_max(num / 10); 	       	


count = 0;
compute_is_prime(num, div)
   if ( div equals 1 )
        return count;
   return (num % div) ?  compute_is_prime(num, div - 1) : (++count);                      

and the call will be compute_is_prime(num, num / 2);

if the function returns 0, then prime, else not.

In this, we basically check from n /2 to 1. if we find that a number divides the given number, then the given number is not prime.

4) Could you elaborate it? i did not quite understand the question.

thank you very much it was extremely helpful. mission almost complete. :)

This article has been dead for over six months. Start a new discussion instead.