he-013
1.000
Challenge · difficulty 1/5
# HumanEval/13
Implement a file **`solution.py`** that completes the function below. Keep the given name and signature; your file must define it at module level.
```python
def greatest_common_divisor(a: int, b: int) -> int:
""" Return a greatest common divisor of two integers a and b
>>> greatest_common_divisor(3, 5)
1
>>> greatest_common_divisor(25, 15)
5
"""
```
<!-- imported from OpenAI HumanEval (HumanEval/13) -->
tests/test_he_013.py
# Auto-generated from OpenAI HumanEval HumanEval/13. Do not edit by hand.
from solution import * # noqa: F401,F403 (prompt helpers may be referenced by tests)
from solution import greatest_common_divisor as candidate
METADATA = {
'author': 'jt',
'dataset': 'test'
}
def check(candidate):
assert candidate(3, 7) == 1
assert candidate(10, 15) == 5
assert candidate(49, 14) == 7
assert candidate(144, 60) == 12
def test_he_013():
check(candidate)
System prompt
You are an expert programmer. Solve the task exactly as specified. Output your solution as fenced code blocks using the required file name(s) and the exact function/type signatures requested. Prefer correctness; do not include prose outside code unless asked.
Proposed solution
```python
def greatest_common_divisor(a: int, b: int) -> int:
""" Return a greatest common divisor of two integers a and b
>>> greatest_common_divisor(3, 5)
1
>>> greatest_common_divisor(25, 15)
5
"""
# Handle negative numbers by taking absolute values
a = abs(a)
b = abs(b)
# Euclidean algorithm
while b != 0:
a, b = b, a % b
return a
```Test output (stdout)
. [100%] 1 passed in 0.01s
Reasoning (chain-of-thought)
The task is to implement a function that calculates the greatest common divisor (GCD) of two integers. This is a classic problem that can be solved using the Euclidean algorithm.
The Euclidean algorithm works as follows:
1. If b is 0, then gcd(a, b) = a
2. Otherwise, gcd(a, b) = gcd(b, a mod b)
Let me trace through the examples:
- gcd(3, 5): gcd(5, 3) -> gcd(3, 2) -> gcd(2, 1) -> gcd(1, 0) = 1 ✓
- gcd(25, 15): gcd(15, 10) -> gcd(10, 5) -> gcd(5, 0) = 5 ✓
I should also consider edge cases:
- Negative numbers: The GCD should be positive
- Zero: gcd(0, 0) is typically undefined, but we can return 0
- One of them is 0: gcd(a, 0) = |a|
Let me write the implementation:
```python
def greatest_common_divisor(a: int, b: int) -> int:
""" Return a greatest common divisor of two integers a and b
>>> greatest_common_divisor(3, 5)
1
>>> greatest_common_divisor(25, 15)
5
"""
# Handle negative numbers by taking absolute values
a = abs(a)
b = abs(b)
# Euclidean algorithm
while b != 0:
a, b = b, a % b
return a
```
This should work correctly for all cases.