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

Improve algorithm to count digits in Long #1548

Merged
merged 1 commit into from
Nov 14, 2024

Conversation

Egorand
Copy link
Collaborator

@Egorand Egorand commented Nov 14, 2024

Based on "Down Another Rabbit Hole" by @romainguy - thanks!

@romainguy
Copy link

🎉

Comment on lines +491 to +512
private val DigitCountToLargestValue = longArrayOf(
-1, // Every value has more than 0 digits.
9L, // For 1 digit (index 1), the largest value is 9.
99L,
999L,
9999L,
99999L,
999999L,
9999999L,
99999999L,
999999999L,
9999999999L,
99999999999L,
999999999999L,
9999999999999L,
99999999999999L,
999999999999999L,
9999999999999999L,
99999999999999999L,
999999999999999999L, // For 18 digits (index 18), the largest value is 999999999999999999.
Long.MAX_VALUE, // For 19 digits (index 19), the largest value is MAX_VALUE.
)
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a slight deviation from the original table proposed in the article:

private val PowersOfTen = longArrayOf(
    0,
    10,
    100,
    1000,
    10000,
    100000,
    1000000,
    10000000,
    100000000,
    1000000000,
    10000000000,
    100000000000,
    1000000000000,
    10000000000000,
    100000000000000,
    1000000000000000,
    10000000000000000,
    100000000000000000,
    1000000000000000000
)

@swankjesse & I discovered that the original table wouldn't work for the Long.MAX_VALUE test case, as it has more digits than 10^18, and 10^19 is outside of the range of Long. The code instead compares against largest numbers that can be represented with a given digit count, which allowed us to fit another entry into the table!

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I saw that and it's a great improvement!

@JakeWharton JakeWharton merged commit 935b3f0 into master Nov 14, 2024
11 checks passed
@JakeWharton JakeWharton deleted the egor.241114.better-count-digits branch November 14, 2024 17:26
@JakeWharton
Copy link
Collaborator

The original code made it up into kotlinx.io. Do you want to send them a PR, too?

@Egorand
Copy link
Collaborator Author

Egorand commented Nov 14, 2024

The original code made it up into kotlinx.io. Do you want to send them a PR, too?

Sure, done! Kotlin/kotlinx-io#413

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

Successfully merging this pull request may close these issues.

3 participants