Skip to content

Instantly share code, notes, and snippets.

@srawlins
Forked from rbranson/pidigits.rb
Created November 17, 2010 20:11
Show Gist options
  • Save srawlins/703982 to your computer and use it in GitHub Desktop.
Save srawlins/703982 to your computer and use it in GitHub Desktop.
# The Computer Language Benchmarks Game
# http://shootout.alioth.debian.org/
# transliterated from Mario Pernici's Python program
# contributed by Rick Branson
# made 'functional' by Sam Rawlins
require "rubygems"
require "gmp"
def gmpz(n)
GMP::Z.new(n)
end
N = gmpz((ARGV[0] || 100).to_i)
i = gmpz(0); k = gmpz(0); ns = gmpz(0)
k1 = gmpz(1)
n,a,d,t,u = [1,0,1,0,0].map { |n| gmpz(n) }
g_zero = gmpz(0)
g_one = gmpz(1)
g_two = gmpz(2)
g_three = gmpz(3)
g_ten = gmpz(10)
loop do
GMP::Z.add(k, k, g_one)
t = n << g_one
GMP::Z.mul(n, n, k)
GMP::Z.add(a, a, t)
GMP::Z.add(k1, k1, g_two)
GMP::Z.mul(a, a, k1)
GMP::Z.mul(d, d, k1)
if a >= n
q = (n*g_three +a)
t = q.fdiv(d)
u = q.fmod(d)
GMP::Z.add(u, u, n)
if d > u
ns = ns * g_ten + t
GMP::Z.add(i, i, g_one)
if i % g_ten == g_zero
puts "#{ns.to_s.rjust(10, '0')}\t:#{i.to_s}"
ns = g_zero
end
break if i >= N
GMP::Z.submul(a, d, t)
GMP::Z.mul( a, a, g_ten)
GMP::Z.mul( n, n, g_ten)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment