SdlS
SdlS

Reputation: 181

Recursion - Java

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));
     }  
}

Upvotes: 0

Views: 822

Answers (2)

Domin
Domin

Reputation: 463

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));
    }
}

Upvotes: 1

jgitter
jgitter

Reputation: 3414

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.

Upvotes: 2

Related Questions