Python Program to Find G.C.D Using Recursion
In this tutorial, you will learn how to Find G.C.D Using Recursion with the if and else statement along with the different operators of the python programming language.
How to Find G.C.D Using Recursion?
Let’s take a look at the source code , here the values are given as input by the user in the code, the if and else statements along with the assignment operators carry out the function.
# Python Program to Find G.C.D Using Recursion def hcf(a, b): if(b == 0): return a else: return hcf(b, a % b) a = int(input("Enter the first integer: ")) b = int(input("\nEnter the second integer: ")) print("\nThe gcd of the two numbers is : ", end="") print(hcf(a, b))
Enter the first integer: Enter the second integer: The gcd of the two numbers is : 12
- At the start, we use
def hcf(a, b):where the
defkeyword is used to define a function and
hcfis used to call the function to get the value of the variable
- We declare an
ifstatement with the condition
(b == 0)where if it is satisfied, using the
returnfunction we return the value of n, if the condition is not satisfied, it moves to the next step which is the
elsestatement where the value obtained after the execution of the equation
hcf(b, a % b)is returned using the
- Here we give the user the option to enter the values and the input values are scanned using the
inputfunction and are stored in the variables
bwith the statements/strings
("Enter the first integer: ")and
("Enter the second integer: "), we use the
intfunction and declare the input value as an integer value.
- In the STDIN section of the code editor the input values are entered.
- We declare a
("\nThe gcd of the two numbers is : ", end="")after which we declare another
(hcf(a, b))where the function
hcfwill display the values which the variables
(a, b)will hold. The
endfunction in the above line of code gives the position where the last line of code should be displayed.
- The end parameter in python is used to append any string at the end of the output of the print statement.
- The input() function allows a user to insert a value into a program, it returns a string value.
- The if and else statements evaluates whether an expression is true or false. If a condition is true, the “if” statement is executed otherwise, the “else” statement is executed.
- The == equality is a comparison operator which returns True is the two items are equal and returns False if not equal.
- The Modulo operator (%) calculates the remainder of dividing two values.
- The colon : at the end of the if and else statement tells Python that the next line of code should only be run if the condition is true.
- The statement for the input function are enclosed in single quotes and parenthesis.
- The \n in the code indicates a new line or the end of a statement line or a string.
- The print statement/string to be displayed in enclosed in double quotes.