Reputation: 1439
I must be failing to wrap my head around the concept of trying to store a value in a recursive method. Solving this using iteration would take seconds, but I am struggling with the recursive call. Basically I am trying to solve: 1/1 + 1/2 + 1/3 ...
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter in the end number for the sequence: ");
int endpoint = input.nextInt();
System.out.println("The value of the sequence is : " + calcSequence(endpoint));
}
public static double calcSequence (int index){
if (index == 0)
return 0;
else
return (1/index) + calcSequence(index - 1);
}
Upvotes: 1
Views: 576
Reputation: 28687
You need to add some explicit type conversions. Your 1/index
is being performed as integer division, and your call is losing all its precision. Simply changing this to 1.0/index
(or 1d/index
to indicate that the 1
should be used as a double
) should get you what you're looking for.
Upvotes: 6