Last active
April 12, 2016 05:01
-
-
Save benoist/ea8f6f014d893bcea0fe to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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