#include<stdio.h>
int f(int,int);
int main()
{
printf("%d",f(20,1));
return 0;
}
int f(int n,int k)
{
if(n==0) return 0;
else if(n%2)return f(n/2,2*k)+k;
else return f(n/2,2*k)-k;
}
how this program is working and generating output as 9....?
Answer / kodam
n=20, k =1
if, else if false. so it will call
f(n/2,2*k)-k ==> f(10,2)-1
if, else if false
f(n/2,2*k)-k ==> f(5, 4)-2
if is false. else if is true
f(n/2,2*k)+k ==> f(2, 8)+4
if, else if false
f(n/2,2*k)-k ==> f(1, 16)-8
if is false. else if is true
f(n/2,2*k)+k ==> f(0, 32)+16
now n is zero.
output
------
-1-2+4-8+16 = 9
| Is This Answer Correct ? | 7 Yes | 0 No |
What are the functions to open and close file in c language?
how to write a program which adds two numbers without using semicolon in c
Are the variables argc and argv are always local to main?
What is boolean in c?
Why is c not oop?
Is both getch() and getchar() functions are similar? if it is similar means why these two functions are used for same usage? if it is not similar means what is the difference?
what is the difference between c and c++?
Write a program to print all permutations of a given string.
What is scope and lifetime of a variable in c?
what is an inline function?
Calculate 1*2*3*____*n using recursive function??
What is the correct declaration of main?