最近、暇つぶしにハッカーランクにはまってます。。。
1. 配列aの最大公倍数にnをかけた値がいくつ配列Bに含まれるかの演習
こちらに良い書き方が載っていたので忘れないようにメモっておきます。
- LCMとは最小公倍数
- GCDとは最大公約数
- Arrayに機能をInject
def getTotalX(a, b)
# Complete this function
# 1. find the LCM of all the integers of array A. 最小公倍数 least common multiple
lcm1 = a.lcm
# 2. find the GCD of all the integers of array B. 最大公約数 greatest common divisor
lcd1 = b.gcd
# 3. Count the number of multiples of LCM that evenly divides the GCD.
count = 0
for m in 1..100 do
if (lcd1 % (lcm1 * m)) == 0 then
count += 1
end
end
puts count
end
class Array
def lcm
self.inject{|a,b| a.lcm(b)}
end
def gcd
self.inject{|a,b| a.gcd(b)}
end
end