konstantin - 2 years ago 109
Java Question

# Function method in java

I am trying to understand a block of code i have how exactly it works. My code is an example of recursion and try to calculate the chance of a prime number as a number of a nth dice rolling outcome. My code is the following:

``````public static double ev3(int sum, int rollsLeft) {

if (rollsLeft == 0) {
if (sum == 3 ){
return 1;
}
else
return 0;
}

double rsum = 0;

for (int i = 1; i <= 6; i++) {
rsum += ev3(sum + i, rollsLeft - 1)/6.0;
}
return rsum;
}
``````

I struggle to understand how the recursion exactly is working and if I am doing what I am suppose to. Why sum takes values beyond six.

EDIT: in the debugging that it goes like that: ev3(1,2) -> ev(2,1) and then instead of ev3(3,0) it goes again to ev3(2,1) any idea why this is happening?

Your function evaluates some custom metric, but if you replace 100 with 1, -50 with 0, and generalize the `sum == 3 || sum == 5 || sum == 7 || sum == 11 || sum == 13 || sum == 17` expression to an `isPrime(sum)` function, you'll be able to calculate the probability of the sum of n dice rolls being a prime number.