javarecursion

Sum of previous numbers in Java using recursion


I'm trying to solve this homework problem:

Write a method called sumOfPreviousN that takes two integers and returns the sum of the first number minus multiples of the second number. For example: Write a method called sumOfPreviousN that takes two integers and returns the sum of the first number minus multiples of the second number. For example, sumOfPreviousN(9, 4) would return 6 because it would add 5 + 1. sumOfPreviousN(20, 6) would return 24 because it would add 14 + 8 + 2.

We haven't learned loops yet, so we're only allowed to use recursion.

Here's what I have so far:

public class help {
    public static int sumOfPreviousN(int num1, int num2) {
        if (num1 <= num2) {
            return num1 + num2;
        } else {
            int subtracted = num1 - num2;
            return subtracted + sumOfPreviousN(subtracted, num2); 
        }
    }
    public static void main(String[] args) {
        int num1 = 20;
        int num2 = 6;
        System.out.println(sumOfPreviousN(num1, num2));
    }
}

It feels like I need to use a 3rd variable that I'm missing, but there's definitely a way! I'm not sure how to, for this example, keep subtracting 6 while keeping track of both the values that are decreasing by 6 AND the values that are being added by the latter.


Solution

  • I think your base case was supposed to be num1 > num2. When num2 is greater or equal, return 0. Otherwise use your current recursion and something like,

    public static int sumOfPreviousN(int num1, int num2) {
        if (num1 <= num2) {
            return 0;
        }
        int subtracted = num1 - num2;
        return subtracted + sumOfPreviousN(subtracted, num2);
    }
    

    Which I tested with your provided test cases,

    System.out.println(sumOfPreviousN(9, 4) == 6);
    System.out.println(sumOfPreviousN(20, 6) == 24);
    

    And got

    true
    true