Java Recursion compilation error -
i fresh student in computer science , study java recursion. unfortunately, academy explains following regarding topic:
- what recursion means.
- there 2 types of cases when using recursive algorithm: base cases , recursive cases , purpose.
- an example of factorial , fibonacci implementation using recursion.
now got following exercise:
two integer numbers called "strangers" if greatest common divisor (aka gtc) only 1". example, numbers 8 , 9 "strangers" because gtc 1. however, 8 , 9 not "strangers" because gtc 2.
please implement recursive method receives array of integers, , returns "true" if every pair numbers in array strangers, , "false" otherwise.
method signature must follows:
public boolean checkgcd(int[] values)
for example:
{3, 5, 7, 11} -> method returns true.
{4, 7, 8, 9} -> method returns false because 4 , 8 not strangers.for assistance, can use following method finding gtc (euclidean algorithm):
private static int gcd(int n, int m){ if (m==0) return n; return gcd(m,n % m); }
in addition, method checkgcd(int[] values) should overloaded...
loops cannot used!
the above can done nested loop, must use recursion!
i understand need use overloaded method gets the array
, lo index
, hi index
.
so came in mind:
@@@@@@
base case: if there @ least 1 pair of numbers in array not strangers, method returns false (no need continue comparison...).
@@@@@@
comparison done in following way: lo index points 1st cell -> hi index points 2nd cell -> comparing -> hi index incremented 1 until reaches last cell of array.
then, lo index incremented 1, , repeating above.
so bottom line, should compare first cell consecutive cells, compare 2nd consecutive cells, 3rd etc...
@@@@@@@@
if pairs of numbers strangers, need else stop recursion. therefore, if pairs strangers, means lo index , hi index point last cell (cause both lo , hi index has incremented gradually, , reach last array cell after comparisons turned out ok i.e strangers).
the following overloaded function:
private static boolean checkgcd(int[] values, int lo, int hi) { if ( (gcd(values[lo], values[hi]) )!= 1 ) return false; else if (lo < values.length-1 && hi < values.length-1) return checkgcd(values, lo, hi+1); else if (lo < values.length-2 && hi == values.length-1) return checkgcd (values, lo+1, lo+2); if (lo == values.length-1 && hi == values.length-1) return true; } -> compiler says "missing return statement"**
the following method exercise requires have, , calls overloaded method recursively.
public static boolean checkgcd(int[] values) { return checkgcd(values, 0, 1); }
when try compile, "missing return statement" points close bracket in overloaded function
but use "return" in overloaded function.
please clarify how fix. sure after compilation error, above overloaded function still not ok.
you compiler error because, if every if
fails, method not return anything. solution add appropriate return
statement when final if
fails.
Comments
Post a Comment