user3002211
user3002211

Reputation: 183

Recursive function to check digits

Write a recursive function to check how many digits in the number can be divided by the digit which is after them. Example: 84963 should return 2, because 8 can be divided by 4 and 6 can be divided by 3. My function doesnt seem to output anything at all.

#include <iostream>

using namespace std;

int fun (int n);

int main()
{
    int n;
    cin >> n;
    cout << fun(n) << endl;
    return 0;
}

int fun(int n){
    int count = 0;
    if (fun(n % 100) % fun(n % 10) == 0)
        count++;
    return count;
}

Upvotes: 0

Views: 1671

Answers (4)

Patrick Kostjens
Patrick Kostjens

Reputation: 5105

Your recursion does not make much sense at the moment. A more logical approach to this would be to see if the last number (so 1 in 321), can currently divide the second last number (so 2 in 321). You could do this by defining a function that checks if that is possible, and recursively passes on the number divided by 10. That function would look something like this:

int fun(int n)
{
  if (n < 10)
    return 0;
  int last = n % 10;
  n = n / 10;
  int secondlast = n % 10;
  if (secondlast != 0 && last != 0 && secondlast % last == 0) 
    return 1 + fun(n);
  else
    return fun(n);
}

Update note: After looking into Vlad from moscow's comment, I moved the last != 0 part of the condition forward, to solve a bug (divide by 0).

The problem Vlad from moscow was talking about is the following: If you want, for example, the part 04 to count as 0, you should use the code as it is above. Otherwise you should remove the secondlast != 0 part.

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

The valid code will be

size_t fun( int n )
{
    const int base = 10;
    int digit = n % base;
    n /= base;

    return ( n == 0 ? 
             0      : 
             ( digit && n % base && !( n % base % digit ) ) + fun( n ) );
}

Upvotes: 0

jcm
jcm

Reputation: 2578

You're not actually updating n value so you get into an infinite loop, on the other hand, your function is, initially, only designed for 3 digits number. I think that it should be something similar to:

int fun(int n, int ant, int count){
    if( n == 0 )
        return count;

    if (ant != 0 &&
             (n%10) % ant == 0)
        count++;

    return fun(n/10, n%10, count);
}

I should work with different number of digits.

Upvotes: 0

ScarletAmaranth
ScarletAmaranth

Reputation: 5101

int countIfDiv(int num) {
    int pair = num % 100;
    int first = pair / 10;
    if (first == 0) return 0;
    int second = pair % 10;
    int next = num / 10;
    return first % second == 0 ? 1 + countIfDiv(next) : 0 + countIfDiv(next);
}

Just pull a pair, try the division, then chop the last number and repeat.

Upvotes: 0

Related Questions