class factor
#num - input number, show - whether to display the result on the screen
def factorization num, show = false
num1 = num
n = 2 # start searching for divisors from 2
while n * n <= num1
if num% n == 0 # if the current number is a divisor, output it
num = num / n
puts n if show
else # otherwise we increase the current number
n + = 1
end
end
end
end gem install RubyInline require 'rubygems'
require 'inline' # connect RubyInline
class Test
# embedded code handler
inline do | builder | # an object of class Inline :: C is passed to the block
builder.c '
static char * test () {
return "Hi from C! :)";
}
'
end
end
puts Test.new.test # prints "Hi from C! :)" c performs the following actions:test as a normal Ruby method. require 'rubygems'
require 'inline'
class FastFactor
inline do | builder |
builder.c '
static void factorization (int num, int show) {
int i = 0;
int num1 = num;
int n = 2;
while (n * n <= num1) {
if (num% n == 0) {
num = num / n;
if (show)
printf ("% d \ n", n);
i ++;
} else {
n ++;
}
}
}
'
end
end f = Factor.new
1000.times {f.factorization 999999}
$ time ruby factor.rb
real 0m1.034s
user 0m1.028s
sys 0m0.004s
f = FastFactor.new
1000.times {f.factorization 999999, false}
time ruby factorfast.rb
real 0m0.116s
user 0m0.092s
sys 0m0.024s
Source: https://habr.com/ru/post/48928/
All Articles