Create solver_factorial.py
Browse files- solver_factorial.py +56 -0
solver_factorial.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
import re
|
| 5 |
+
from typing import Optional
|
| 6 |
+
|
| 7 |
+
from models import SolverResult
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def solve_factorial(text: str) -> Optional[SolverResult]:
|
| 11 |
+
lower = (text or "").lower()
|
| 12 |
+
|
| 13 |
+
if "!" not in text and "factorial" not in lower:
|
| 14 |
+
return None
|
| 15 |
+
|
| 16 |
+
# n!
|
| 17 |
+
m = re.search(r"(\d+)\s*!", text)
|
| 18 |
+
if m:
|
| 19 |
+
n = int(m.group(1))
|
| 20 |
+
if n < 0:
|
| 21 |
+
return None
|
| 22 |
+
result = math.factorial(n)
|
| 23 |
+
return SolverResult(
|
| 24 |
+
domain="quant",
|
| 25 |
+
solved=True,
|
| 26 |
+
topic="factorial",
|
| 27 |
+
answer_value=str(result),
|
| 28 |
+
internal_answer=str(result),
|
| 29 |
+
steps=[
|
| 30 |
+
"Use n! = n × (n−1) × ... × 1.",
|
| 31 |
+
],
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
# "how many trailing zeros in 100!"
|
| 35 |
+
m = re.search(r"trailing zeros.*?(\d+)\s*!", lower)
|
| 36 |
+
if m:
|
| 37 |
+
n = int(m.group(1))
|
| 38 |
+
count = 0
|
| 39 |
+
power = 5
|
| 40 |
+
while power <= n:
|
| 41 |
+
count += n // power
|
| 42 |
+
power *= 5
|
| 43 |
+
return SolverResult(
|
| 44 |
+
domain="quant",
|
| 45 |
+
solved=True,
|
| 46 |
+
topic="factorial_trailing_zeros",
|
| 47 |
+
answer_value=str(count),
|
| 48 |
+
internal_answer=str(count),
|
| 49 |
+
steps=[
|
| 50 |
+
"Trailing zeros come from factors of 10 = 2×5.",
|
| 51 |
+
"There are always more 2s than 5s in a factorial.",
|
| 52 |
+
"Count factors of 5 using n//5 + n//25 + n//125 + ...",
|
| 53 |
+
],
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
return None
|