Skip to content

Instantly share code, notes, and snippets.

@tbuehlmann
Created October 27, 2009 18:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tbuehlmann/219797 to your computer and use it in GitHub Desktop.
Save tbuehlmann/219797 to your computer and use it in GitHub Desktop.
AJAXy Sieve of Eratosthenes with Sinatra
require 'index'
run Sinatra::Application
!!!
%html{:xmlns => "http://www.w3.org/1999/xhtml"}
%head
%script{:type => "text/javascript", :src => "js/prototype.js"}
%body
%h1 Wieviele Primzahlen gibt es zwischen 0 und der Eingabe?
%input{:type => 'text', :id => 'myval', :size => '10'}
%input{:type => 'button', :value => 'Prime it!', :onClick => "ajaxRequest('/ajax', 'val='+$F('myval')); $('result').innerHTML = 'loading'"}
#result
require 'rubygems'
require 'sinatra'
require 'haml'
require 'timeout'
@@liste = {}
get '/' do
haml :index
end
get '/ajax' do
if request.xhr?
n = params[:val].to_i
if @@liste.has_key?(n)
return @@liste[n]
else
begin
Timeout.timeout 15 do
neu = sieb(n)
@@liste[n] = neu
@output = neu.to_s
end
rescue Timeout::Error
@output = "Timeout"
end
return @output
end
end
end
helpers do
def sieb(x)
liste = []
prim = []
for i in (2..x) do
liste << i
end
until liste.length == 0
prim << liste[0]
del = liste[0]
for i in liste do
if i % del == 0
liste.delete(i)
end
end
end
return prim.length.to_s
end
end
Prototype in here
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment