he-024
1.000
Challenge · difficulty 1/5
# HumanEval/24
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 largest_divisor(n: int) -> int:
""" For a given number n, find the largest number that divides n evenly, smaller than n
>>> largest_divisor(15)
5
"""
```
<!-- imported from OpenAI HumanEval (HumanEval/24) -->
tests/test_he_024.py
# Auto-generated from OpenAI HumanEval HumanEval/24. Do not edit by hand.
from solution import * # noqa: F401,F403 (prompt helpers may be referenced by tests)
from solution import largest_divisor as candidate
METADATA = {
'author': 'jt',
'dataset': 'test'
}
def check(candidate):
assert candidate(3) == 1
assert candidate(7) == 1
assert candidate(10) == 5
assert candidate(100) == 50
assert candidate(49) == 7
def test_he_024():
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
Looking at this problem, I need to find the largest divisor of `n` that is smaller than `n` itself.
Let me think through the approach:
1. For any number n > 1, I want to find the largest proper divisor
2. The largest proper divisor would be n divided by its smallest prime factor
3. For example, with n=15: factors are 1,3,5,15. The largest proper divisor is 5 (which is 15/3)
4. For a prime number like 7: the only proper divisor is 1
I can optimize this by checking divisors from sqrt(n) downwards to find the largest one efficiently.
Actually, let me think more carefully:
- I want the largest divisor d where d < n and n % d == 0
- This is equivalent to finding the smallest prime factor of n, then dividing n by that factor
Let me trace through examples:
- n=15: factors are 1,3,5,15. Largest proper divisor = 5 (15/3)
- n=12: factors are 1,2,3,4,6,12. Largest proper divisor = 6 (12/2)
- n=7: prime, factors are 1,7. Largest proper divisor = 1
Here's my approach:
1. Check for divisors from 2 up to sqrt(n)
2. When I find the first divisor d, then n/d is the largest proper divisor
3. If no divisor found, n is prime and answer is 1
```python
def largest_divisor(n: int) -> int:
""" For a given number n, find the largest number that divides n evenly, smaller than n
>>> largest_divisor(15)
5
"""
if n <= 1:
return None
# Find the smallest divisor >= 2
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return n // i
# If no divisor found, n is prime, so largest proper divisor is 1
return 1
```Test output (stdout)
. [100%]
1 passed in 0.01s