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 Rust (1.15.1) (judge verdict: Runtime Error)

use std::cmp::min;

fn read<T: std::str::FromStr>(
    stdin_lock: &mut std::io::StdinLock,
    buf: &mut Vec<u8>,
    delimiter: u8,
) -> T {
    buf.clear();
    let l = std::io::BufRead::read_until(stdin_lock, delimiter, buf).unwrap();
    buf.truncate(l - 1); // remove delimiter
    let s = unsafe { std::str::from_utf8_unchecked(&buf) };
    s.parse().unwrap_or_else(|_| panic!("read"))
}

fn main() {
    let stdin = std::io::stdin();
    let mut stdin_lock = stdin.lock();
    let mut buf: Vec<u8> = Vec::new();
    let n: i64 = read(&mut stdin_lock, &mut buf, b'\n');

    let mut av: Vec<i64> = Vec::new();
    let mut m = n;
    let mut a = 2;
    let mut j = 1;
    loop {
        if a * a > n {
            break;
        }
        if m % a == 0 {
            av.push(a.pow(j));
            m /= a;
            j += 1;
        } else {
            a += 1;
            j = 1;
        }
    }
    let mut ans = n - 1;
    for i in 0..av.len() {
        let a = av[i];
        ans = min(ans, (n / a - 1) + (a - 1));
        for j in 0..av.len() {
            let a = av[i] * av[j];
            if n % a == 0 {
                ans = min(ans, (n / a - 1) + (a - 1));
            }
        }
    }
    println!("{}", ans);
}