user2283672
user2283672

Reputation: 21

logical issue in recursion euler

I'd like to the euler number e for a number n inputed by the user, there's something wrong with the logical part, I can't seem to get the correct answer of 2.5 when inputting 2, instead i get 2. In fact I always get an answer of 2 no matter what the input is. The problem is in the euler method because the factorial prints the correct answer. here is the code.

import java.util.*;

 public class pract5ex3 {
    public static int fact (int n){
    if (n==0 || n==1){
            return 1;
    }
    else {
    return n*fact(n-1);
    }

}
public static double constantRec(int n){
    if (n == 0){

    return 1;
    }
    else {

    return 1/fact(n)+constantRec(n-1);
    }
}

public static void main (String []args) {
    Scanner s= new Scanner (System.in);
    System.out.println("enter number");
    int n =s.nextInt();

    int factorial = pract5ex3.fact(n);
    double euler = pract5ex3.constantRec(n);
    System.out.println(factorial);
    System.out.println(euler);
}

}

Upvotes: 0

Views: 606

Answers (2)

Howard
Howard

Reputation: 39207

The expression 1/fact(n) does integer division which will yield zero if factorial is greater than one. Simply change it to 1.0/fact(n).

Upvotes: 2

BobTheBuilder
BobTheBuilder

Reputation: 19294

Beware of Integer division.

Use:

1.0/fact(n)

To get the double value.

Upvotes: 3

Related Questions