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;
}
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:
- If
b
is 0, it returns 1 because any number raised to the power of 0 is 1. - It recursively calls itself with
b
divided by 2. This is based on the principle thata^(2n) = (a^n)^2
. - The result of the recursive call is squared and stored in
ans
. - If
b
is odd (i.e.,b%2
is 1),ans
is multiplied bya
. - Finally,
ans
is returned.
Now, let's calculate fun(2, 10)
:
b
is not 0, so it doesn't return 1.- It calls
fun(2, 5)
. fun(2, 5)
callsfun(2, 2)
.fun(2, 2)
callsfun(2, 1)
.fun(2, 1)
callsfun(2, 0)
.fun(2, 0)
returns 1.fun(2, 1)
squares 1 to get 1, multiplies it by 2 (becauseb
is odd) to get 2, and returns 2.fun(2, 2)
squares 2 to get 4 and returns 4 (becauseb
is even).fun(2, 5)
squares 4 to get 16, multiplies it by 2 (becauseb
is odd) to get 32, and returns 32.fun(2, 10)
squares 32 to get 1024 and returns 1024 (becauseb
is even).
So, fun(2, 10)
returns 1024.
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 =
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.