recursion - Sequence 1, 3, 8, 18, 38, 78 from a recursive function -
i'm trying write recursive function in java display n element in mathematical number sequence (1 3 8 18 38 78).
this i've managed far:
public static int recfunc(int i) { if(i==1) { return 1; } if(i==2) { return 2+recfunc(i-1); } if(i==3) { return 5+recfunc(i-1); } if(i>3) { return ((2^(i-3))*5)+recfunc(3); } return 0; }
to calculate n(>3), add 2^(i-3) each step(i>3) , add 8 in end. so, 6th element, have calculation: 40 + 20 + 10 + 8 = 78.
the problem above code calculates increase in number between 2 n(s) , ads 5 + 2 + 1 (8) it, doesn't apply previous steps (20 + 10).
update:
i'm getting somewhere, still doesn't should.
public static int recfunc(int i, boolean param) { if(param==false) { if(i==1) { return 1; } if(i==2) { return 2+recfunc(i-1, false); } if(i==3) { return 5+recfunc(i-1, false); } if(i>3) { param = true; } } if(param==true) { if(i==4) { return ((2^(i-3))*5)+recfunc(i-1, false); } else { return ((2^(i-3))*5)+recfunc(i-1, true); } } return 0; }
the problem power function. ^ in java not mean raise power. means xor.
you can use java's math.pow()
int recfunc(int i) { if(i==1) { return 1; } if(i==2) { return 2+recfunc(i-1); } if(i==3) { return 5+recfunc(i-1); } if(i>3) { return ((math.pow(2,(i-3))*5)+recfunc(i-1)); } return 0; }
hope helps.
Comments
Post a Comment