Home > Software engineering >  What's the role of the function Unknown in this code
What's the role of the function Unknown in this code

Time:06-14

from math import sqrt
def unknown(A, B):
    if A < 2 or A % B == 0:
        return False
    elif B > sqrt(A):
        return True
    else:
        return unknown(A, B 1)
A = int(input("A="))
B = int(input("B="))
p = unknown(A, B)
print(p)

What's the role of this code knowing that

  • unknown(5, 2): True
  • unknown(6, 2): False
  • unknown(7, 2): True
  • unknown(9, 2): False

CodePudding user response:

The function "unknown" is a function that can be called recursively and is called recursively if the initial values that are entered do not satisfy the first two conditions that are tested (the "if" and the "elif" tests). For instance, when one enters the values of A = 9 and B = 2 neither of the first two test conditions are met within the initial call of the function. Therefore, the value of B is incremented by one (and now has a value of 3) and the function is called again within itself. This time, 9 being wholly divisible by 3 makes the condition "A%B==0" true, so the function can return a value of "False". Since this recursive call happens to be the fallback, it subsequently continues the returns up the function call stack and the function is completed.

Hope that clarifies things.

Regards.

CodePudding user response:

As you pass the input to your function, it will process :

    if A<2 or A%B==0:   #case 1
        return False
    elif B>sqrt(A):     #case 2
        return True
    else:
        return unknown(A,B 1)

If no conditions match, then the last function will call the function with (A, B 1) this will continue until case 1 & case 2 does not satisfy.

  • Related