Skip to content

Implement Integer.sqrt for large integers #3872

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
merged 1 commit into from
May 23, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion spec/tags/core/integer/sqrt_tags.txt

This file was deleted.

12 changes: 11 additions & 1 deletion src/main/ruby/truffleruby/core/integer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,17 @@ def self.try_convert(obj)
def self.sqrt(n)
n = Primitive.rb_to_int(n)
raise Math::DomainError if n.negative?
Math.sqrt(n).floor
return Math.sqrt(n).floor if n < 0xfffffffffffff

shift = n.bit_length / 4
x = sqrt(n >> (2 * shift)) << shift
x = (x + n / x) / 2
xx = x * x
while xx > n
xx -= 2 * x - 1
x -= 1
end
x
Copy link
Member

Choose a reason for hiding this comment

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

Wondering how the constant 0xfffffffffffff was chosen. Is it based on benchmarking results?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Larger is better as long as Math.sqrt(n).floor returns correct value.
0xfffffffffffff is 52bit integer and double has 53bit precision.

If n is larger than 0xfffffffffffff == 0x4000000**2-1, Math.sqrt(n).floor might not return correct value.
Integer.sqrt(0x4000001**2-1) should return 0x4000001 - 1
Math.sqrt(0x4000001**2-1).floor is 0x4000001

end

private def upto_internal(val)
Expand Down
Loading