483 views
2 votes
2 votes
How many asterisks (*) in terms of k will be printed by the following C
function, when called as count(m) where m = 3k? Justify your answer.
Assume that 4 bytes are used to store an integer in C and k is such that
3k can be stored in 4 bytes.
void count(int n)
{
printf("*");
if(n>1)
{
count(n/3);
count(n/3);
count(n/3);
}
}

1 Answer

3 votes
3 votes

Lets take simple case when n=9, you will have a recursion tree as follows-

              9

    3        3          3

1 1 1   1 1 1    1 1 1

This is nothing but perfect 3-ary tree.

At each node, you have a printf statement. So we need to count no of nodes in such tree.

No. of levels(x) for given n in such tree will be ceil(log3n).

Total no of nodes in perfect 3-ary tree = (3x-1)/2 = (3ceil(log3n)-1)/2

In this question n=3k, So total no of printf statements(total no of nodes in recursion tree)=(3ceil(log33k)-1)/2

Related questions

2 votes
2 votes
1 answer
1
rupamsardar asked Aug 30, 2023
484 views
#include <stdio.h int f(int x) { if(x%2==0) { return f(f(x-1)); } else return (x++); } int main() { printf("%d",f(12)); ret...
0 votes
0 votes
1 answer
2
SHWETAV SUMAN asked Oct 6, 2022
328 views
i have typed the following code but when i executed it the solution was not according to my expectation.unsigned short int y= -9; int iy=y; printf(“%d”,iy); solutio...
0 votes
0 votes
3 answers
3
ykrishnay asked May 30, 2022
1,061 views
int main(){extern int a = 20;printf("%d",a); }//why this gives error but followig code is not extern int a =20;int main(){printf("%d",a); } //why this happens that first ...
0 votes
0 votes
0 answers
4
ykrishnay asked May 20, 2022
384 views
What is stream in c programming ? as i read file io in c programming so thats where i read “stream” word so what stream means ? thank you