Home > OS >  print the number of numbers between 2 numbers and divided by the number 7 using recursion in c
print the number of numbers between 2 numbers and divided by the number 7 using recursion in c

Time:01-03

I want to convert this non-recursive function to recursive function. How can I do it? I must find the number of numbers between 2 numbers which are divisible by 7.

void count_divisors2(int min, int max) {

    //Variable to store the counter
    int counter = 0, i;
    
    // Running a loop from A to B and check
    // if a number is divisible by M.
    for (i = min; i <= max; i  ) {
        if (i % 7 == 0)
            counter  ;
    }
    printf("%d", counter);
}

CodePudding user response:

Instead of printing the number, you should return the count:

Non recursive version:

int count_divisors2(int min, int max) {

    //Variable to store the counter
    int counter = 0, i;
    
    // Running a loop from A to B and check
    // if a number is divisible by M.
    for (i = min; i <= max; i  ) {
        if (i % 7 == 0)
            counter  ;
    }
    return counter;
}

Recursive version:

int count_divisors2(int min, int max) {
    if (min > max)
        return 0;
    else
        return (min % 7 == 0)   count_divisors2(min   1, max);
}

Direct version:

int count_divisors2(int min, int max) {
    if (min <= max) {
        if (min >= 0)
            return (max / 7) - (min / 7)   (min % 7 == 0);
        else
        if (max >= 0)
            return (max / 7) - (min / 7)   1;
        else
            return (max / 7) - (min / 7)   (max % 7 == 0);
    } else {
        return 0;
    }
}
  • Related