Skip to content

Instantly share code, notes, and snippets.

@fujidig
Created April 30, 2016 12:15
Show Gist options
  • Select an option

  • Save fujidig/3e47e57a41b154aaea757a0805bf3442 to your computer and use it in GitHub Desktop.

Select an option

Save fujidig/3e47e57a41b154aaea757a0805bf3442 to your computer and use it in GitHub Desktop.
# Babylonian method
def isqrt(n)
return 0 if n == 0
s, t = 1, n
while s < t
s *= 2
t /= 2
end
begin
t = s
s = (n / s + s) / 2
end while s < t
t
end
def triangular(n)
n * (n + 1) / 2
end
# x (x + 1) / 2 <= n を変形すると
# (2x + 1)^2 <= 8n + 1
def triangular_inv(n)
a = isqrt(8 * n + 1)
if a % 2 == 0
(a - 2) / 2
else
(a - 1) / 2
end
end
def istriangular(n)
triangular(triangular_inv(n)) == n
end
def issquare(n)
isqrt(n)**2 == n
end
1000.times do |i|
[1, -1].each do |a|
n = 2 ** i + a
if istriangular(n)
puts "#{n} is triangular"
end
if issquare(n)
puts "#{n} is square"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment