Kotlin Program: Find the GCD of two numbers
Write a Kotlin program to find the GCD (Greatest Common Divisor) of two numbers.
Sample Solution:
Kotlin Code:
Sample Output:
GCD of 28 and 16: 4
Explanation:
In the above exercise -
- In "main()" function "number1" and "number2" variables represent the two numbers for which we want to find the GCD.
- The "findGCD()" function takes the two numbers as arguments and calculates their GCD.
- Inside the findGCD() function, we initialize variables "num1" and "num2" with the values of "number1" and "number2" respectively.
- We use a while loop to repeatedly divide num1 by "num2" until "num2" becomes zero.
- In each iteration, we store the value of "num2" in a temporary variable temp and update "num2" to the remainder of "num1" divided by num2.
- We then updated "num1" to "temp".
- This process continues until "num2" becomes zero, at which point "num1" will hold the GCD of the original "number1" and "number2".
- Finally, we return the value of "num1", which is the GCD.
Kotlin Editor:
Previous: Count even and odd elements in an array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics