简体   繁体   English

Java-使用递归求和一个数字,该数字与该数字的差和3的倍数之差

[英]Java - Using recursion to sum a number with the difference of that number and multiples of 3

I am doing exercises with algebraic formulas to practice the use of recursion in Java. 我正在使用代数公式进行练习,以练习Java中递归的使用。

I am trying to write a method that returns the result of n + (n - 3) + (n - 6) + (n - 9) ... + 0. 我正在尝试编写一种返回n +(n-3)+(n-6)+(n-9)... + 0的结果的方法。

For example, when n = 7, the result should be 12. When n = 10, the result should be 22. 例如,当n = 7时,结果应为12。当n = 10时,结果应为22。

So far, this is what I have: 到目前为止,这就是我所拥有的:

public static int sumDownBy3(int n)
{

    if(triSum <= 0)
    {
        return sum;
    }

    sum = n;
    triVar += 3;
    triSum = (n - triVar);

    return sumDownBy3(n + triSum);
}

However, when I compile and run it, it does not return the expected result. 但是,当我编译并运行它时,它不会返回预期的结果。 How may I fix this method to correctly apply the formula I am trying to emulate? 如何解决此方法以正确应用我要模拟的公式?

So, here are a few tips to hopefully get you going considering the comments by childofsoong and Jonny Henly. 因此,这里有一些技巧可以帮助您考虑childofsoong和Jonny Henly的评论。

What you are looking for is simply: 您正在寻找的只是:

f(n) = n + f(n-3) for n > 0. 当n> 0时f(n) = n + f(n-3)

Your recursive function should just check if n is <= 0. If it is, return 0. Else return the variable n + another call to your function with n-3. 您的递归函数应该只检查n是否<=0。如果是,则返回0。否则返回变量n +用n-3再次调用函数。

Hope this helps without giving too much away. 希望这对您有所帮助。

Since this isn't an assignment, just practice, then here is a working solution based off the information given in your question. 由于这不是一项作业,请练习,然后基于您问题中给出的信息,这是一个可行的解决方案。 This solution works for all n , however n <= 0 will always return 0 . 该解决方案适用于所有n ,但是n <= 0将始终返回0

public static int sumDownBy3(int n) {
    if (n <= 0) {
        return 0;
    }

    return n + sumDownBy3(n - 3);
}

Instead of having an extra parameter or global/class variables keeping track of the sum, this example just uses the stack to keep track of the sum. 该示例没有使用额外的参数或全局/类变量来跟踪总和,而仅使用堆栈来跟踪总和。 One downside to this approach is that for a very, very large number the stack could overflow and/or the program could lock up. 这种方法的缺点是,对于非常大量的堆栈,堆栈可能会溢出和/或程序可能会锁定。

Output: 输出:

sumDownBy3(7)  = 12
sumDownBy3(10) = 22
sumDownBy3(9)  = 18

Breakdown for sumDownBy3(10) : sumDownBy3(10)细目:

sumDownBy3(10): 10 !<= 0 -> return 10 + sumDownBy3(10 - 3)
sumDownBy3( 7):  7 !<= 0 -> return  7 + sumDownBy3( 7 - 3)
sumDownBy3( 4):  4 !<= 0 -> return  4 + sumDownBy3( 4 - 3)
sumDownBy3( 1):  1 !<= 0 -> return  1 + sumDownBy3( 1 - 3)
sumDownBy3(-2): -2  <= 0 -> return  0

So 0 + 1 + 4 + 7 + 10 ='s 22

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM