recursion - Coding a recurrence relation in Java -
i writing code calculates recursive mathematical problem, called foo.
the condition should be,
if n < 4
: foo(n) = n
if n >= 4
: foo(n) = n + foo(n - 1) + 2*foo(n-2)
.
public class foo { public static int foo(n) { if(n < 4) { return n; } else if(n >= 4) { } } public static void main(string[] args) { } }
i stuck here... final purpose state values of foo(1), foo(2), foo(3), foo(4), foo(5), foo(6), foo(7).
also, allowed put main method in foo class?
the following function 1 you're looking for:
public static int bar(int n){ if(n < 4){ return n; } return n + bar(n - 1) + 2*bar(n-2); }
first of all, if want function call main
directly, must static
, because you're not allowed call non-static method static context.
static
functions (methods) called on classes, not on objects. therefor, there no need create object - execute foo.bar(anyint)
.
then, need check if n smaller 4 - if is, return n
.
there no need else
clause, because if returned inside if, won't execute more code function, return
means exit function now
.
then, please follow java naming strategies, start class name capital letter (foo
instead of foo
). foo
perfect name field, variable or method, not class.
the code should in end like:
public class foo { public static int bar(int n){ if(n < 4){ return n; } return n + bar(n - 1) + 2*bar(n-2); } public static void main(string[] args) { (int = 1; < 8; i++) { system.out.println("bar(" + + ") " + foo.bar(i)); } } }
the output be:
>bar(1) 1 >bar(2) 2 >bar(3) 3 >bar(4) 11 >bar(5) 22 >bar(6) 50 >bar(7) 101
Comments
Post a Comment