Use the above recursive formula for calculating countB and countS using previous values
for ( $ i = 2 ; $ i <= $ N ; $ i ++ ) { $ prev_countB = $ countB ; $ prev_countS = $ countS ; $ countS = $ prev_countB + $ prev_countS ; $ countB = $ prev_countS ; }