Given the triangle number sequence: 1, 3, 6, 10, 15, 21, 28, 36, 45, … The recur
ID: 3842962 • Letter: G
Question
Given the triangle number sequence: 1, 3, 6, 10, 15, 21, 28, 36, 45, …
The recursive triangle function below calculates the triangle number at term n where n is assumed to be greater than 0 (i.e. n starts at 1). However, there is something wrong with the recursive triangle Java function below. For example, if you call the function “triangle(3);”, you would expect it to return 6 (because it is the 3rd term in the sequence), but this function doesn’t.
a) If the current incorrect function was called as “int result = triangle(4);”, what would the value be in result?
b) What code change(s) would you make to fix the triangle function?
// Assume term > 0 public int triangle(int term) { if (term == 1) return term; return term * triangle(term – 1); }
Explanation / Answer
1) For the given function triangle(4) will retrun value as per below
term = 4
if(term==1) false
return 4*triangle(4-1) // from below we get traingle(3) is 6 , hence this will retunr 4*6 i.e 24
term = 3
term==1 false
return 3*triangle(2) //from below we got triangle(2) is 2 hence this will return 3*2 i.e. 6
term==1 false
retunr 2*triangle(1) //we get below triangle(1) is 1 hence from here will return 2*1
term==1 true return 1
now backtrack and fille the value
so int result = triangle(4)
result = 24
2) To correct this function if you see above we go intermediate value of triangle(4) , which are 4,3,2,1 now instead of multiplying then if we sum all we get 4+3+2+1 = 10 which is the expected result.
Hence the correct function will be
public int triangle(int term)
if(term ==1)
return term;
return term + triangle(term-1);
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.