Skip to main content

GATE CSE 2021Algorithms › Recursion & Recurrence RelationsVerified

GATE CSE 2021 PYQ: Consider the following ANSI C \text{ANSI C} ANSI C program #include <stdio.h> int foo ( int x , int y , int…

Consider the following ANSI C\text{ANSI C} program

  1. #include <stdio.h>
  2. int foo(int x, int y, int q) 
  3. {
  4. if ((x<=0) && (y<=0))
  5. return q;
  6. if (x<=0)
  7. return foo(x, y-q, q);
  8. if (y<=0)
  9. return foo(x-q, y, q);
  10. return foo(x, y-q, q) + foo(x-q, y, q);
  11. }
  12. int main( )
  13. {
  14. int r = foo(15, 15, 10);
  15. printf(“%d”, r);
  16. return 0;
  17. }

The output of the program upon execution is _________

    Answer

    60

    Approach

    Treat q=10 as the unit of recursion. Let F(x,y)=foo(x,y,10). The base value is 10 whenever x &lt;= 0 or y &lt;= 0, and for positive x,y the recurrence is F(x,y)=F(x,y-10)+F(x-10,y). Compute the needed states bottom-up.

    The recurrence evaluates to 60; equivalently, there are six terminal paths in the recursion tree, each contributing q=10.

    Reviewed by GateIQ Editorial Team: IIT & IISc Alumni.