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 )?
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
bis 0, it returns 1 because any number raised to the power of 0 is 1. - It recursively calls itself with
bdivided 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
bis odd (i.e.,b%2is 1),ansis multiplied bya. - Finally,
ansis returned.
Now, let's calculate fun(2, 10):
bis 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 (becausebis odd) to get 2, and returns 2.fun(2, 2)squares 2 to get 4 and returns 4 (becausebis even).fun(2, 5)squares 4 to get 16, multiplies it by 2 (becausebis odd) to get 32, and returns 32.fun(2, 10)squares 32 to get 1024 and returns 1024 (becausebis even).
So, fun(2, 10) returns 1024.
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
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.