ruby - Test works, but it's too slow for the test -
hi guys spent while pairing partner solving problem https://www.codewars.com/kata/playing-on-a-chessboard/train/ruby
it passes every test has stderr @ end saying:
process terminated. took longer 12000ms complete. can please advise on how speed following code or make more efficient?
def game(n) # lowest common multiplier mult = (1..2*n).to_a.reduce(1,:lcm) y = 1 x = 1 # numerator sum numsum = 0 while y <= n while x <= n # numsum += x * mult / (x + y) x += 1 end x = 1; y += 1 end array = [rational(numsum, mult).numerator, rational(numsum, mult).denominator] if array[1] == 1 [array[0]] else array end end
note following part of code:
while y <= n while x <= n numsum += x * mult / (x + y) x += 1 end x = 1; y += 1 end note have 2 nested loops, each 1 n iterations.
means code has complexity of o(n²) (you can read here).
thus, if call game function high value of n, code may hang.
i suggest try rethink algorithm.
exists more efficient way solve problem.
Comments
Post a Comment