Problem:
Score : 300 points

Problem Statement

Takahashi is standing on a multiplication table with infinitely many rows and columns.

The square (i,j) contains the integer i \times j. Initially, Takahashi is standing at (1,1).

In one move, he can move from (i,j) to either (i+1,j) or (i,j+1).

Given an integer N, find the minimum number of moves needed to reach a square that contains N.

Constraints

2 \leq N \leq 10^{12}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the minimum number of moves needed to reach a square that contains the integer N.

Sample Input 1

10

Sample Output 1

5

(2,5) can be reached in five moves. We cannot reach a square that contains 10 in less than five moves.

Sample Input 2

50

Sample Output 2

13

(5, 10) can be reached in 13 moves.

Sample Input 3

10000000019

Sample Output 3

10000000018

Both input and output may be enormous.

Solution in Haskell (GHC 7.10.3) (judge verdict: Wrong Answer)

import Data.List

main = do
  li <- getLine
  let n = read li
  let ans = compute n
  print ans

{-
双曲線xy=nのOに近い格子点を探す、つまりy=xに近いところ。
素因数分解して、xとyに交互に因数を与えていくぐらいしかやれることはなさそう。
-}

compute :: Int -> Int
compute n = loop 1 1 $ primeFactors n
  where
    loop a b (c:d:ps) = loop (a*c) (b*d) ps
    loop a b [c] = step2 (a*c,b)
    loop a b [] = step2 (a,b)
    step2 (a,b) = a + b - 2

primes = 2 : 3 : 5 : sieve [(9,3),(10,5)] [7,9..]

sieve ((q,p):qps) xxs@(x:xs) =
  case compare q x of
    LT -> sieve qps1 xxs
    EQ -> sieve qps1 xs
    GT -> x : sieve (insert (x+x,x) qps) xs
  where
    qps1 = insert (q+p,p) qps

primeFactors n = loop n primes
  where
    loop 1 _ = []
    loop n pps@(p:ps)
      | r == 0 = p : loop q pps
      | q < p  = [n]
      | True   = loop n ps
      where (q,r) = divMod n p