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

What is output for fun(2, 10)?

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;  
}
🧐 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

Predict the output of the following C Programming Snippet:#include <stdio.h>int main() {  int a = 8, b = 6;  printf("%d %d", a & b, a | b);  return 0;}

Predict the output for the given code for func(8, 2) ?int func(int a, int b){    int c;    c = a << b;    return c;}Select one:a. 16b. 8c. 4d. 32

Understanding Unary operators#include <stdio.h>void main() { int a = 10, b; b = a++ + ++a; printf("%d %d\n", a, b);}What is the a = b =

find the output of given code.#include <stdio.h>int main(){int a,b=110,c=20;printf("%d",a=b-=c*=5);return 0;}

Understanding Comma operator#include <stdio.h>int main(void) { int a; a = (1, 2, 3); printf("%d", a); return 0;}What is the value of a =

1/1

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.