Python Basics

HCF using Recursion

Detailed guide and Python implementation for the 'HCF using Recursion' problem.

問題提起

Write a function hcf(a, b) that computes the Highest Common Factor (HCF), also known as the Greatest Common Divisor (GCD), of two positive integers a and b using recursion. Use the Euclidean algorithm: HCF(a, b) = HCF(b, a % b), with the base case HCF(a, 0) = a.

制約
  • 1 <= a, b <= 10^6

Example 1
Input
a = 12, b = 8
Output
4
Explanation

12 = 4*3, 8 = 4*2. The largest common factor is 4.

Example 2
Input
a = 54, b = 24
Output
6
Explanation

54 = 6*9, 24 = 6*4. HCF is 6.

Example 3
Input
a = 17, b = 13
Output
1
Explanation

17 and 13 are both prime and share no common factors other than 1.

Need a Hint?
Consider using Recursion-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

解決する準備はできましたか?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

エディタで開く
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推奨される Python リソース

関連するインタラクティブなチュートリアル、チートシート、コード比較で知識を深めてください。