https://projecteuler.net/problem=85
å·¦ä¸ã®ç¹ãå
±æããé·æ¹å½¢ã®é¢ç©ã®åè¨ã¨åãã§ãã
é·æ¹å½¢ã®é«ããhãå¹
ãwã¨ããã¨é¢ç©ã®åè¨ã¯
hãå°ããã»ãããæé©ãªwãæ±ãã¦ããã°ããã§ãã
import sys #################### library #################### fn int_sqrt(n: Int) -> Int: var x = 1 x = (x + n // x) // 2 while True: var x1 = (x + n // x) // 2 if x1 >= x: return x x = x1 #################### process #################### fn find_opt_width(h: Int, N: Int) -> Int: var sh = h * (h + 1) // 2 var w = (-1 + int_sqrt(1 + 8 * N // sh)) // 2 var sw1 = w * (w + 1) // 2 var sw2 = (w + 1) * (w + 2) // 2 if N - sh * sw1 < sh * sw2 - N: return w else: return w + 1 fn f(N: Int) -> Int: var nearest_area = 0 var nearest_value = 0 for h in range(1, N): var w = find_opt_width(h, N) if w < h: break var value = h * (h + 1) // 2 * w * (w + 1) // 2 if abs(value - N) < abs(nearest_value - N): nearest_value = value nearest_area = h * w return nearest_area fn main() raises: var args = sys.argv() var N = atol(args[1]) print(f(N))