Skip to content

Instantly share code, notes, and snippets.

@benoist
Last active April 12, 2016 05:01
Show Gist options
  • Save benoist/ea8f6f014d893bcea0fe to your computer and use it in GitHub Desktop.
Save benoist/ea8f6f014d893bcea0fe to your computer and use it in GitHub Desktop.
require "big_int"
struct BigInt2 < Int
def initialize(num : Int::Signed)
if LibC::Long::MIN <= num <= LibC::Long::MAX
LibGMP.init_set_si(out @mpz, num)
else
LibGMP.init_set_str(out @mpz, num.to_s, 10)
end
end
def +(other : BigInt2)
LibGMP.add(mpz, self, other)
self
end
def to_s
String.new(to_cstr)
end
def to_s(io)
str = to_cstr
io.write Slice.new(str, LibC.strlen(str))
end
private def mpz
pointerof(@mpz)
end
private def to_cstr
LibGMP.get_str(nil, 10, mpz)
end
def to_unsafe
mpz
end
end
def fibonacci(n)
a, b = BigInt.new(0), BigInt.new(1)
n.times { a, b = b, a + b }
a
end
start = Time.now
fib = fibonacci 500_000
puts Time.now - start
def fibonacci2(n)
a, b = BigInt2.new(0), BigInt2.new(1)
n.times { a, b = b, a + b }
a
end
start = Time.now
fib2 = fibonacci2 500_000
puts Time.now - start
puts fib.to_s == fib2.to_s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment