Recursive function taking ages to run
<p>I profiled my code and found that my program spent roughly 85% of the time executing this particular recursive function. The function aims to calculate the probability of reaching a set of states in a markov chain, given an initial position (x,y). </p>

<pre><code>private static boolean condition(int n){
    int i = 0;
    while ( n &gt;= i){
        if( n == i*4 || n == (i*4 - 1))
            return true;
            i++;
        }
    return false;
}

public static double recursiveVal(int x, int y, double A, double B){

    if(x&gt; 6 &amp;&amp; (x- 2 &gt;= y)){ return 1;}
    if(y&gt; 6 &amp;&amp; (y- 2 &gt;= x)){ return 0;}
    if(x&gt; 5 &amp;&amp; y&gt; 5 &amp;&amp; x== y){ return (A*(1-B) / (1 -(A*B) - ((1-A)*(1-B))));}

    if(condition(x+ y)){
        return (recursiveVal(x+1, y,A,B)*A + recursiveVal(x, y+1,A,B)*(1-A));
    }
    else{
        return (recursiveVal(x+1, y,A,B)*(1-B) + recursiveVal(x,y+1,A,B)*B);
    }
}
</code></pre>

<p>I was once told that 99% of recursive functions could be replaced by a while loop. I'm having trouble doing this though. Does anyone know how I could improve the execution time or rewrite this as a iterative loop?</p>

<p>Thanks</p>
