-
Notifications
You must be signed in to change notification settings - Fork 2
[integer][decimal] Implement factorial() for BigInt and BigDecimal
#254
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| # ===----------------------------------------------------------------------=== # | ||
| # Copyright 2025-2026 Yuhao Zhu | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| # ===----------------------------------------------------------------------=== # | ||
| # | ||
| # Implements special functions for the BigDecimal type | ||
| # | ||
| # ===----------------------------------------------------------------------=== # | ||
|
|
||
| """Implements functions for special operations on BigDecimal objects.""" | ||
|
|
||
| from decimo.bigdecimal.bigdecimal import BigDecimal | ||
| from decimo.errors import ValueError | ||
|
|
||
| # Extra significant digits carried during a rounded factorial, on top of the | ||
| # requested precision and the digit count of `n`. Covers the rounding error | ||
| # that accumulates over the `n` intermediate products. | ||
| comptime FACTORIAL_GUARD_DIGITS = 9 # word size | ||
|
|
||
| # Largest argument accepted by `factorial`. Even 10^6 already needs ~10^6 | ||
| # multiplications, so anything beyond it is impractical with the simple | ||
| # iterative product. The cap also keeps the value within Mojo's `Int` range, | ||
| # so an out-of-range argument raises a clear error instead of an `Int` | ||
| # overflow. (A faster algorithm, e.g. binary splitting, could lift this.) | ||
| comptime FACTORIAL_MAX_INPUT = 1_000_000 | ||
|
|
||
|
|
||
| def factorial(x: BigDecimal, precision: Int = 0) raises -> BigDecimal: | ||
| """Calculates the factorial of a non-negative integer value. | ||
|
|
||
| Args: | ||
| x: The non-negative integer value to take the factorial of. | ||
| precision: Significant digits for the result. `0` (the default) | ||
| computes the exact factorial with no rounding. A positive value | ||
| rounds the intermediate products to a bounded working width, | ||
| which lowers the cost for large `x`, and returns `precision` | ||
| correct significant digits. | ||
|
|
||
| Returns: | ||
| `x!`, the product of all positive integers up to `x` (`0! == 1`). | ||
| Exact when `precision == 0`. | ||
|
|
||
| Raises: | ||
| ValueError: If `x` is not an integer, is negative, or is larger than | ||
| `FACTORIAL_MAX_INPUT` (10^6). | ||
|
|
||
| Notes: | ||
|
|
||
| The value must currently fit in a Mojo `Int`. Arbitrarily large | ||
| arguments will be supported later. | ||
| """ | ||
| if not x.is_integer(): | ||
| raise ValueError( | ||
| message="Factorial is only defined for integer values.", | ||
| function="factorial()", | ||
| ) | ||
| if x < BigDecimal(0): | ||
| raise ValueError( | ||
| message="Factorial is not defined for negative numbers.", | ||
| function="factorial()", | ||
| ) | ||
| if x > BigDecimal(FACTORIAL_MAX_INPUT): | ||
| raise ValueError( | ||
| message=( | ||
| "Factorial argument is too large to compute (must be <= 10^6)." | ||
| ), | ||
| function="factorial()", | ||
| ) | ||
|
|
||
| # `truncate` gives a scale-0 BigDecimal, so integer values written with a | ||
| # fractional part (e.g. "5.00") convert cleanly to `Int`. | ||
| var n = Int(x.truncate()) | ||
| if precision <= 0: | ||
| # Exact: full-width products, no rounding. | ||
| var result = BigDecimal(1) | ||
| for i in range(2, n + 1): | ||
| result = result.multiply(BigDecimal(i)) | ||
| return result^ | ||
|
forfudan marked this conversation as resolved.
|
||
|
|
||
| # Rounded: keep every product at `precision + guard` significant digits, | ||
| # where the guard also grows with the number of digits in `n`. Round the | ||
| # final result back to `precision` (HALF_EVEN, via multiply-by-one). | ||
| var working_precision = ( | ||
| precision + String(n).byte_length() + FACTORIAL_GUARD_DIGITS | ||
| ) | ||
| var result = BigDecimal(1) | ||
| for i in range(2, n + 1): | ||
| result = result.multiply(BigDecimal(i), working_precision) | ||
| return result.multiply(BigDecimal(1), precision) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| # ===----------------------------------------------------------------------=== # | ||
| # Copyright 2025-2026 Yuhao Zhu | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| # ===----------------------------------------------------------------------=== # | ||
| # | ||
| # Implements special functions for the BigInt type | ||
| # | ||
| # ===----------------------------------------------------------------------=== # | ||
|
|
||
| """Implements functions for special operations on BigInt objects.""" | ||
|
|
||
| from decimo.bigint.bigint import BigInt | ||
| from decimo.errors import ValueError | ||
|
|
||
| # Largest argument accepted by `factorial`. Even 10^6 already needs ~10^6 | ||
| # multiplications, so anything beyond it is impractical with the simple | ||
| # iterative product. The cap also keeps the value within Mojo's `Int` range, | ||
| # so an out-of-range argument raises a clear error instead of an `Int` | ||
| # overflow. (A faster algorithm, e.g. binary splitting, could lift this.) | ||
| comptime FACTORIAL_MAX_INPUT = 1_000_000 | ||
|
|
||
|
|
||
| def factorial(x: BigInt) raises -> BigInt: | ||
| """Calculates the factorial of a non-negative integer value. | ||
|
|
||
| Args: | ||
| x: The non-negative integer value to take the factorial of. | ||
|
|
||
| Returns: | ||
| `x!`, the product of all positive integers up to `x` (`0! == 1`). | ||
|
|
||
| Raises: | ||
| ValueError: If `x` is negative or larger than `FACTORIAL_MAX_INPUT` | ||
| (10^6). | ||
|
|
||
| Notes: | ||
|
|
||
| The value must currently fit in a Mojo `Int`. Arbitrarily large | ||
| arguments will be supported later. | ||
| """ | ||
| if x < BigInt.zero(): | ||
| raise ValueError( | ||
| message="Factorial is not defined for negative numbers.", | ||
| function="factorial()", | ||
| ) | ||
| if x > BigInt(FACTORIAL_MAX_INPUT): | ||
| raise ValueError( | ||
| message=( | ||
| "Factorial argument is too large to compute (must be <= 10^6)." | ||
| ), | ||
| function="factorial()", | ||
| ) | ||
|
|
||
| var n = Int(x) | ||
| var result = BigInt.one() | ||
| for i in range(2, n + 1): | ||
| result *= BigInt(i) | ||
| return result^ | ||
|
forfudan marked this conversation as resolved.
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| # ===----------------------------------------------------------------------=== # | ||
| # Test BigDecimal special functions (factorial) | ||
| # ===----------------------------------------------------------------------=== # | ||
|
|
||
| from std import testing | ||
| from decimo.bigdecimal.bigdecimal import BigDecimal | ||
|
|
||
|
|
||
| def test_factorial_exact() raises: | ||
| """Test exact factorial (precision == 0).""" | ||
| testing.assert_equal(String(BigDecimal(0).factorial()), "1") | ||
| testing.assert_equal(String(BigDecimal(1).factorial()), "1") | ||
| testing.assert_equal(String(BigDecimal(5).factorial()), "120") | ||
| testing.assert_equal(String(BigDecimal(10).factorial()), "3628800") | ||
| testing.assert_equal( | ||
| String(BigDecimal(30).factorial()), | ||
| "265252859812191058636308480000000", | ||
| ) | ||
|
|
||
|
|
||
| def test_factorial_integer_with_scale() raises: | ||
| """Test that an integer value written with a fractional part (e.g. | ||
| "5.00") is accepted.""" | ||
| testing.assert_equal(String(BigDecimal("5.00").factorial()), "120") | ||
|
|
||
|
|
||
| def test_factorial_rounded() raises: | ||
| """Test the rounded mode returns `precision` significant digits.""" | ||
| testing.assert_equal( | ||
| String(BigDecimal(30).factorial(10)), "2.652528598E+32" | ||
| ) | ||
|
|
||
|
|
||
| def test_factorial_non_integer_raises() raises: | ||
| """Test that a non-integer argument raises.""" | ||
| var raised = False | ||
| try: | ||
| _ = BigDecimal("5.5").factorial() | ||
| except: | ||
| raised = True | ||
| testing.assert_true(raised, "factorial of a non-integer should raise") | ||
|
|
||
|
|
||
| def test_factorial_negative_raises() raises: | ||
| """Test that a negative argument raises.""" | ||
| var raised = False | ||
| try: | ||
| _ = BigDecimal(-1).factorial() | ||
| except: | ||
| raised = True | ||
| testing.assert_true(raised, "factorial of a negative value should raise") | ||
|
|
||
|
|
||
| def test_factorial_too_large_raises() raises: | ||
| """Test that an argument above the cap raises.""" | ||
| var raised = False | ||
| try: | ||
| _ = BigDecimal(2_000_000).factorial() # above the 10^6 cap | ||
| except: | ||
| raised = True | ||
| testing.assert_true(raised, "factorial above the cap should raise") | ||
|
|
||
|
|
||
| def main() raises: | ||
| testing.TestSuite.discover_tests[__functions_in_module()]().run() |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.