1)What would happen if we call gcd(m,n) with m positive and n negative in the following definition?
def gcd(m,n):
if m < n:
(m,n) = (n,m)
if (m % n) == 0:
return(n)
else:
diff = m-n
return (gcd(max(n,diff),min(n,diff)))
2)What can we say about a number n if h(n) returns True for the function h given below?
def h(n):
for i in range(2,n):
if n%i == 0:
return(True)
return(False)
3)What does f(120,13) return for the following function defintion?
def f(m,n):
ans = 1
while (m - n >= 0):
(ans,m) = (ans*2,m-n)
return(ans)
Reason : In above program, while loop terminates when the value of m became less then the value of n. So, by understanding this loop if we calculate initially m/n = 120/13 = 9. Effectively what will be calculated is 2 raised to the answer of m^n if we see only the math path(ans=ans*2 for 9 times). By calculation, it will be 512( 2 ^ 9).
4)What does g(9000,3) return for the following function definition?
def g(x,y):
val = 0
while (x > y):
(val,x) = (val+1,x/y)
return(val)
Answer : 8
Reason : Basically, the program is simple and calculates how many times loop will execute. So if the value of ( x/y <= y ) then loop will terminate. So by calculation 9000/3^8 it gives answer more then 3 but when we will calculate 9000/3^9(answer less than y which is 3) then loop will terminate. So the final answer is 8. Simple Maths Equation :- (x/y^n), where n is val.