简体   繁体   English

用Java递归定义一个序列

[英]Define a sequence recursively in Java

Need help with this problem, I am very bad at recursion. 在这个问题上需要帮助,我在递归方面很不好。 I need to write a method that does this: 我需要编写一个执行此操作的方法:

The input variable X is an integer between 1 and 50. The function should return as Y the X-th term of a sequence defined recursively by: 输入变量X是1到50之间的整数。该函数应以Y形式返回由以下项递归定义的序列的第X个项:

f(1) = 1 f(2) = 3 f(X) = 2*f(X-1) – 2*f(X-2) for X = 3,4,5,...

Your function code should use recursion (not a loop) 您的函数代码应使用递归(而不是循环)

TBH I dont even know where to get started. TBH我什至不知道从哪里开始。 Any help would be appreciated. 任何帮助,将不胜感激。 Here is my current code: 这是我当前的代码:

package p1parta;

import java.util.Scanner;

public class RecursiveSeq
{
    public static void main(String args[])
    {
       System.out.println("Please enter a number:");
       Scanner input = new Scanner(System.in);

       int x = input.nextInt();

       System.out.println(sequence(x));
    }

    public static int sequence(int x)
    {
        if(x == 1){
           return 1;
        }
        if (x == 2){
           return 3;
        }
        return 2 * sequence(x - 1) - 2 * sequence(x - 2);
    }
}

I tried to implement the solution shown but the output I get from the program do not match what I am calculating by hand. 我尝试实现所示的解决方案,但是从程序中获得的输出与我手工计算的结果不匹配。 In fact just testing inputs 3,4,5,and 6 The only one that matches is 5 实际上,仅测试输入3、4、5和6,唯一匹配的输入是5

Your problem is a perfect use case for recursion. 您的问题是一个完美的递归用例。 In general the recursive pattern is: 通常,递归模式为:

func(context)
    if simple case
        return simple answer
    else
        call func(simpler context)
        and return combined results

Have a go at implementing using this pattern and come back if you have issues. 尝试使用此模式实施,如果有问题请回来。

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

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