• edited by
3,514 views
3 3 votes
#include<stdio.h>
int fun(int a,int b)
{
    if(b==0)
    return 0;
    if(b%2==0)
    return fun(a+a,b/2);
    return fun(a+a,b/2)+a;
}
int main()
{
    printf("%d",fun(9,11));
    return 0;
}

2 Answers

Best answer
2 2 votes

99 is the correct answer


The given code is actually doing just multiplication without using '*'. We can $a*b$ by adding $a$ to $a$, $b-1$ times. The given code is a smarter way to do this reducing the time complexity to $O(\log b)$ instead of $O(b)$ for the naive approach. The same code also works for doing power function, if we replace $+$ with $\times$.

• edited by
Position:
Show:

Related questions

1 1 vote
1 answers 1 answer
1.5k
1.5k views
srestha asked Aug 7, 2016
1,521 views
What will be outputint main() { char str[10]="GATE 2016"; int length=strlen(str); str[length]='\0'; for(i=0;str[i];i++) printf("%c",str[i]); return 0; }