Skip to content
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

Arbitrary-Precision Arithmetic base #1034

Open
jxu opened this issue Feb 2, 2023 · 4 comments
Open

Arbitrary-Precision Arithmetic base #1034

jxu opened this issue Feb 2, 2023 · 4 comments

Comments

@jxu
Copy link
Contributor

jxu commented Feb 2, 2023

Article: Arbitrary-Precision Arithmetic

Problem:
Is using base 10^9 really better than using a base like 2^30? Seems like modulo and carry flag operations would be much more efficient, at the cost of slower decimal I/O.

@adamant-pwn
Copy link
Member

I'm not sure, base conversion is typically quite slow

@jxu
Copy link
Contributor Author

jxu commented Feb 3, 2023

I guess it depends which is done more - base conversion or arithmetic. I think GMP uses full words as its "base" to speed up operations.

@jxu
Copy link
Contributor Author

jxu commented Feb 15, 2023

@jakobkogler what do you think?

@jakobkogler
Copy link
Member

I personally use the base $10^4$ in my big-integer library.
The intuition was, that multiplications between two digits can be done with 32-bit integers.
But it's probably a stupid idea, as operations like addition are then twice as slow.
And I don't think I've ever benchmarked if multiplications are really that much faster.
However it was fast enough for any big-integer problems that I ever solved.

The obvious algorithm for base conversion is $O(n^2)$ for an n-digit number.
With divide and conquer you can get down to $O(n \log^2 n)$: see here https://codeforces.com/blog/entry/95047
Back then I didn't know about this trick, so the choice for a power of 10 was the only way.

Also, modulo operations are not that bad. For addition/subtraction you don't need to do a modulo operation, you can just compare ala if (result >= mod) result -= mod;.
And for multiplication: if the compiler knows the modulus at compile time, it can optimize modulo operations (e.g. by Strength reduction).

However you are correct, that if you do a lot of operations, then a binary base will be faster.

Anyway, big integer problems in competitive programming don't have super tight limits. So it doesn't matter too much which version we present on the website. (Although the D&C trick might be interesting either way, regardless if it leads to a better way or not).

If you want to know the difference, why not implement two versions yourself and publish the results?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants