Skip to content

Commit 929a034

Browse files
authored
Simplify Range.disjoint?/2 intersection arithmetic (#15884)
Find the first intersection using modulo in the later progression. Remove floor divisions and redundant bounds checks. Assisted-by: Codex:GPT-6
1 parent 1d15942 commit 929a034

1 file changed

Lines changed: 12 additions & 9 deletions

File tree

lib/elixir/lib/range.ex

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -497,15 +497,18 @@ defmodule Range do
497497
{gcd, u, v} = Integer.extended_gcd(-step1, step2)
498498

499499
if rem(first2 - first1, gcd) == 0 do
500-
c = first1 - first2 + step2 - step1
501-
t1 = Integer.floor_div(-c * u, step2)
502-
t2 = Integer.floor_div(-c * v, step1)
503-
t = max(t1 + 1, t2 + 1)
504-
x = div(c * u + t * step2, gcd) - 1
505-
y = div(c * v + t * step1, gcd) - 1
506-
507-
x < 0 or first1 + x * step1 > last1 or
508-
y < 0 or first2 + y * step2 > last2
500+
factor = div(first1 - first2, gcd)
501+
502+
# The first nonnegative index in the later progression gives
503+
# the first intersection at or beyond both starts.
504+
intersection =
505+
if first1 >= first2 do
506+
first1 + Integer.mod(factor * u, div(step2, gcd)) * step1
507+
else
508+
first2 + Integer.mod(factor * v, div(step1, gcd)) * step2
509+
end
510+
511+
intersection > last1 or intersection > last2
509512
else
510513
true
511514
end

0 commit comments

Comments
 (0)