In A not so easy problem I looked at using Python with Excel (via pyxll) to work with very long integers, using the MPMath package. For high precision calculations involving decimal values MPMath is required, but for simple operations entirely on integers the native Python integers can be of any length, so this post looks at using Python integers from Excel. The examples below have been added to the py_Numpy spreadsheet, which can be downloaded with the associated Python code from:

Note that the Python code comes in two version, with or without calls to the Numba just-in-time compiler. I am currently using the latter, since the standard installation of Numba does not yet support Python 3.11.

The first example uses Python integers to return the factors of integers of any length:

The code for the Factorization function was adapted from a Stackoverflow discussion:

Integer factorization in python

The function returns the factors of any given integer, followed by the calculation time. The first example (row 6) took about 20 seconds to return the results, so has been converted to text, but the example on row 9 is any active function, which takes less than 0.08 seconds to run.

The factorization function calls gcd(), which returns the greatest common divisor of two integers, and can be called from Excel using py_gcd:

```
@xl_func
@xl_arg('n1', 'str')
@xl_arg('n2', 'str')
@xl_return('str')
def py_gcd(n1, n2):
n1 = int(n1)
n2 = int(n2)
return gcd(n1, n2)
```

The two integers are passed as strings (since Excel can’t handle very long integers), then converted to integers and passed to gcd(). The integer return value is than converted to a string for return to Excel.

Three functions are provided for integer division:

int_mod(n1, n2) returns the remainder of n1 divided by n2. The example confirms that 112969501600351915928116

is indeed an exact factor of

11193123069125255733930404403495413078162092382549228

int_floor(n1, n2) returns the integer part of n1, divided by n2, using the Python // operator, whereas int_div(n1, n2) returns the complete result of the division, including any decimal part, using the / operator. Note that division of two integers using / in Python always returns a float, even if the divisor is an exact factor, as in this case. The code returns the resulting value to Excel as a string, but all digits after the 16th are lost. To retain the full precision with long integers use the int_floor function.

The multiplication, addition and subtraction functions are more straightforward, since the results of these operations will always be another integer:

Pingback: py_Numpy update and using Numba | Newton Excel Bach, not (just) an Excel Blog