Mathematical Algo
def gcd(a, b)
if a == 0
return b
elsif b == 0
return a
else
q = a / b
r = a % b
a = b
b = r
gcd(a, b)
end
end
puts gcd(270, 192)
puts gcd(192, 270)
def binary(num)
int = []
i = 0
q = num
while q > 0
int[i] = q % 2
q = q / 2
i += 1
end
int.reverse!
end
def mod_exponent(base, exponent: exp, mod: mod)
binary = binary(exponent).reverse!
output = []
temp = 0
binary.each_with_index do |element, ind|
value = 2 ** ind
temp = value == 1 ? temp = (base * value) % mod : temp = (temp * temp) % mod
output << temp if element != 0
end
product = output.inject(1) { |product, element| product * element }
mod_exp = product % mod
end
puts "binary of 1234 = #{binary(1234)}"
puts mod_exponent(98765, exponent: 1234, mod: 123557)
class PrimeNumber
def initialize(num)
@num = num + 1
@composite = Array.new(@num, 0)
@composite[0] = 1
@composite[1] = 1
@primes = []
end
def sieve
sr = Math.sqrt(@num).ceil
sr.times do |index|
if @composite[index] != 1
start = index * index
while start < @num
@composite[start] = 1
start += index
end
end
end
@composite.each_with_index do |num, index|
@primes << index if num != 1
end
@primes
end
end
prime = PrimeNumber.new(100)
puts prime.sieve