Recursion - Java

我的未来我决定 提交于 2019-12-23 02:55:11

问题


I am working on a program where I have to use recursion to calculate the sum of 1/3 + 2/5 + 3/7 + 4/9 + ... + i / (2i + 1). However, I am not sure how to make my program show the term that must be added in order to reach the number enter by the user. For example. If I enter 12, I want to know how many terms of the series [1/3 + 2/5 + 3/7 + 4/9 + ... + i / (2i + 1)] were added to get approximately to the number 12.

What I don't want to get is the sum of inputting 12 which in this case is 5.034490247342584 rather I want to get the term that if I were to sum all numbers up to that term I would get something close to 12.

Any help will be greatly appreciated!

This is my code

import java.util.Scanner;
public class Recursion {
public static void main(String[] args) {

    double number;
    Scanner input = new Scanner(System.in);

    System.out.println("Enter a value=  ");
    number = input.nextInt();

    System.out.println(sum(number) + " is the  term that should be added in order to reach " + number);

}

public static double sum(double k) {
    if (k == 1) 
        return 1/3;
    else 
        return ((k/(2*k+1))+ sum(k-1));
     }  
}

回答1:


I don't think that this problem should be solved using recursion, but... if you need to implement it on that way, this is a possible solution:

import java.util.Scanner;

public class Recursion {
    public static void main(String[] args) {

        double number;
        Scanner input = new Scanner(System.in);

        System.out.println("Enter a value=  ");
        number = input.nextInt();

        double result = 0;
        double expectedValue = number;

        int k = 0;
        while (result < expectedValue) {
            k++;
            result = sum(k);
        }

        System.out.println(k
                + " is the  term that should be added in order to reach "
                + number + " (" + sum(k) + ")");

    }

    public static double sum(double k) {
        if (k == 1)
            return 1 / 3;
        else
            return ((k / (2 * k + 1)) + sum(k - 1));
    }
}



回答2:


You have this question kind of inside out. If you want to know how many terms you need to add to get to 12, you'll have to reverse your algorithm. Keep adding successive k / (2k + 1) for larger and larger k until you hit your desired target. With your current sum method, you would have to start guessing at starting values of k and perform a sort of "binary search" for an acceptably close solution.



来源:https://stackoverflow.com/questions/23347681/recursion-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!