def ternary_search_tree(left, right) loop_cnt = 100 loop_cnt.times do if yield((left * 2 + right) / 3) < yield((left + right * 2) / 3) right = (left + right * 2) / 3 else left = (left * 2 + right) / 3 end end (left + right) / 2 end T = gets.to_i def f(a, c, x) b = a % c k = a / c k2 = k + 1 cost = 0 cost += (c - b) * (k ** 2 + x) cost += b * (k2 ** 2 + x) cost end T.times do x, a = gets.split.map(&:to_i) right = 1 left = a ** 2 ans = ternary_search_tree(right, left) { |k| f(a, k, x) } puts f(a, ans, x) end