Skip to content

Instantly share code, notes, and snippets.

@pen
Created July 9, 2017 08:20
Show Gist options
  • Save pen/a4f5471c7e2ff3c3c1130f5f8c4ba08c to your computer and use it in GitHub Desktop.
Save pen/a4f5471c7e2ff3c3c1130f5f8c4ba08c to your computer and use it in GitHub Desktop.
巨大な整数のN乗根を求める。 某CTFで使った
#!/usr/bin/env ruby
# vim:fileencoding=utf-8
# xのn乗根
def root(x, n)
r = 0
a = 1 << (Math.log(x) / n / Math.log(2))
while a > 0
ra = r | a
d = x - ra ** n
return ra if d == 0
r = ra if d > 0
a >>= 1
end
return nil
end
# xはパイプで、nは引数で指定する
# 例: echo 1727094849536 | ruby n-root.rb 7
x = STDIN.read.to_i
n = ARGV[0].to_i
puts root(x, n) || '整数の答えはない'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment