0

Can anyone help me convert this code to make it run recursively? I'm not exactly sure how. The goal of the code is to count the amount of numbers in an array are divisible by k.

int[] a = {1,2,3,4,5,6,9}
int k = 3;
int count;
for (int i = 0;i <a.length; i ++){
    if (a[i] % 3 == 0){
        count ++;
    }
}

return count;
1
  • 2
    For reference, this is not a good fit for recursion. At least not in Java. A recursive solution wouldn't be any simpler or less error-prone than an iterative one. Commented Oct 13, 2011 at 2:23

2 Answers 2

1

The trick is to find what's changing with each loop iteration, and passing that into the recursive method:

int count(int[] array, int k, int i){
    if(i>=array.length)
        return 0;
    boolean divisible = array[i] % k == 0;
    return count(array, k, i+1) + (divisible?1:0);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, I was wondering what that ? mark in the return statement meant. Also, just checking, the Big O for this is O(n) right? It depends on the size of the array.
Showing that it's O(n) is easy if you show that it is called exactly n times by setting and using a loop invariant. a?b:c is shorthand for if a {b;} else {c;}
1

No need to use recursion. You can simply check whether each member of the list is divisible by 3. Then count the number of Trues. In Mathematica this is straightforward.

a = {1, 2, 3, 4, 5, 6, 9};
Count[Divisible[#, 3] & /@ a, True]

This returns: 3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.