Knowee
Questions
Features
Study Tools

int fun(int a,int b ){ if( !b ) return 1 int ans= fun(a,b/2) ans=ans*ans if( b%2 ) ans=(ans * a) return ans}What is output for fun ( 2,10 )?

Question

int fun(int a,int b ){ if( !b ) return 1 int ans= fun(a,b/2) ans=ans*ans if( b%2 ) ans=(ans * a) return ans}What is output for fun ( 2,10 )?

🧐 Not the exact question you are looking for?Go ask a question

Solution

The function fun is a recursive function that calculates the power of a number. It takes two arguments a and b where a is the base and b is the exponent.

Here's how it works:

  1. If b is 0, it returns 1 because any number raised to the power of 0 is 1.
  2. It recursively calls itself with b divided by 2. This is based on the principle that a^(2n) = (a^n)^2.
  3. The result of the recursive call is squared and stored in ans.
  4. If b is odd (i.e., b%2 is 1), ans is multiplied by a.
  5. Finally, ans is returned.

Now, let's calculate fun(2, 10):

  1. b is not 0, so it doesn't return 1.
  2. It calls fun(2, 5).
  3. fun(2, 5) calls fun(2, 2).
  4. fun(2, 2) calls fun(2, 1).
  5. fun(2, 1) calls fun(2, 0).
  6. fun(2, 0) returns 1.
  7. fun(2, 1) squares 1 to get 1, multiplies it by 2 (because b is odd) to get 2, and returns 2.
  8. fun(2, 2) squares 2 to get 4 and returns 4 (because b is even).
  9. fun(2, 5) squares 4 to get 16, multiplies it by 2 (because b is odd) to get 32, and returns 32.
  10. fun(2, 10) squares 32 to get 1024 and returns 1024 (because b is even).

So, fun(2, 10) returns 1024.

This problem has been solved

Similar Questions

What will be the output of the given program?int fun(int x){int b;if(x==1 || x==0)return 1;elseb=x*fun(x-2);return b;}void main(){int x=6;printf("%d", fun(x));}Options42483640

int  func( int num) {      int a = num, r =0;      while (num > 0) {        r = r * 10 + num % 10;            num /= 10;      }     return r;                  }What will be the output for func(123) ?

#include"stdio.h"int fun1(int ,int );void main(){int a=10,b=20,sum,z=5;z=fun1(a,b);printf("x=%d y=%d\n",a,b);printf("z=%d\n",z++);}int fun1(int a,int b){a=a+b;b=a+b;int sum=a+b;printf("a=%d b=%d sum=%d\n",a,b,sum);return sum;}(i) What value of x and y will be displayed?(ii) What value of z will be displayed

What will be the output of the following program?#include<stdio.h>int main() {     int fun(int);     int i = fun(10);     printf("%d\n", --i);     return 0; } int fun(int i) { return (i++);}Select one:810119

What will be the output of the following pseudo code a=3, b=2?1. 2. Integer funn (Interger a, Integer b)3. if(b<4 && a<4)4. b=b+35. b=(a+c)+b6. return funn (a+1,b) + funn(b, a)-a7. End if8. return a+b -1

1/3

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.