![]() |
1) What is the value of g(728) for the function below?
def g(y):
b=0
while y >= 3:
(y,b)= (y/3,b+1)
return(b)
solution) 5
here y=728,
since y > 3,
a) (y, b)= (728/3,0+1) = ( 242.6 , 1)
b) from a) we see that y is 242.6, hence it is again > 3
so now (y,b)= ( 242.6/3 , 1+1 ) = ( 80.8 , 2 )
c) from b) we see that y is 80.8, hence it is > 3
so now (y,b) = ( 80.8/3 , 2+1 ) = ( 26.9 , 3 )
d) from c) we see that y is 26.9, hence it is >3
so now, (y,b)= ( 26.9/3 , 3+1) = ( 8.9 , 4 )
e) from d) we see that, y is still >3
so now (y , b) = (8.9/3 , 4+1) = ( 2.9 , 5)
f) from e) we can see that y is < 3 so b= 5+0 =5
hence the loop will get terminated at y= 2.9 and the value of b will be 5.
2) What is f (90)- f (89), given the definition of f below?
def f(n):
s=0
for i in range (2,n):
if n%i==0 and i%2==1:
s=s+1
return(s)
solution) From the above program the range of i will be (2,90)from the next step of the program we can see that remainder of (n/i) should be zero and remainder of (i/2) should be 1, so we will require the factors of 90 as n=90 which are:3,5,6,9,10,15,18,30,45 and 90. We need to select the value that i can take from the factors of 90 such that i when divided by 2 gives the remainder 1. Hence i will take the values ( 3,5,9,15,45 )
a) i=3 ; s=0+1
b) i=5 ; s=1+1=2
c) i=9 ; s=2+1=3
d) i=15; s=3+1=4
e) i= 45 ; s=4+ 1=5
3) Consider the following function h.
def h(n):
s=true
for i in range (1,n+1):
if i*i==n:
s=false
return(s)
The function h(n) given above returns false for a positive number n , if and only if
1) n is odd no
2) n is a prime no
3) n is perfect sq
4) n is composite no
solution) Let us consider cases where n takes a prime no, perfect square , composite no & odd no.
case 1) n takes prime value ; n=5
there lies no value of i, in the range (1,6) for which i*i=n (i.e. i*i=5).
Hence it will return true.
case 2) n takes odd value; n= 21
there lies no value of i, in the range of (1,21) for which i*i = n .
Hence it will return true.
case 3) n takes perfect square ; n=9
Here for i=3 in the range (1,10) i*i=n (i.e. 3*3=9).
Hence it will return FALSE.
case 4) n takes a composite value ; n= 6
there lies no value of i, in the range of (1,21) for which i*i = n .
Hence it will return true.
Therefore , the given program will return false only when n is a perfect square.
4) consider the following function fpp.
def foo(m)
if m==0:
return(0)
else:
return(m+foo(m-1))
which of the following is correct?
1) the function always terminates with f(n) = factorial of n
2) the function always terminates with f(n) = n(n+1)/2
3) the function terminates for non negative n with f(n) = factorial of n
4) the function terminates for non negative n with f(n) = n(n+1)/2
solution) This code uses recursive method to compute the sum of n non negative numbers.Here we consider non negative as the program wont terminate if m is negative and foo(m-1) will keep going on if m is negative.

0 Comments