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 C# (Mono 4.6.2.0) (judge verdict: Wrong Answer)

// ReSharper disable ArrangeTypeMemberModifiers
// ReSharper disable ConvertIfStatementToSwitchStatement
// ReSharper disable FunctionRecursiveOnAllPaths
// ReSharper disable InconsistentNaming
// ReSharper disable InlineOutVariableDeclaration
// ReSharper disable InvertIf
// ReSharper disable JoinDeclarationAndInitializer
// ReSharper disable MemberCanBeMadeStatic.Global
// ReSharper disable MemberCanBeMadeStatic.Local
// ReSharper disable NonReadonlyMemberInGetHashCode
// ReSharper disable PossibleNullReferenceException
// ReSharper disable RedundantUsingDirective
// ReSharper disable SuggestVarOrType_BuiltInTypes
// ReSharper disable SuggestVarOrType_Elsewhere
// ReSharper disable TailRecursiveCall
// ReSharper disable UnusedMember.Global
// ReSharper disable UnusedMember.Local
// ReSharper disable UseObjectOrCollectionInitializert

#if true && UTAKA_LOCAL

//#if false
#define UTAKA_DEBUG
#endif

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Numerics;
using System.Runtime.InteropServices;

namespace UtakaApp
{
    public partial class Program
    {
        //=========================================================================================
        // Answer
        //=========================================================================================

        public const string SiteName    = "AtCoder";
        public const string ContestName = "abc144";
        public const string ProblemName = "C";

        public const int Mod = 1000000007;

        public long       N;
        public List<long> list;

        public long best = 0;
        public long ans  = 0;
        public long sqr  = 0;

        public int ListLen;

        public void Solve()
        {
            N = cin.ReadLong;

            var map = FactorizeAsMapLong(N);

            sqr = (long)Math.Sqrt(N);

            list = new List<long>();

            foreach (var pair in map)
            {
                for (int i = 0; i < pair.Value; i++)
                {
                    list.Add(pair.Key);
                }
            }

            ListLen = list.Count;

            best = long.MaxValue;

            Dfs(1, 0);

            long other = N / ans;

            cou.WriteLine(ans + other - 2);
        }

        public void Dfs(long curr, int index)
        {
            if (index >= ListLen)
            {
                var abs = Math.Abs(sqr - curr);

                if (abs < best)
                {
                    best = abs;
                    ans  = curr;
                }

                return;
            }

            Dfs(curr * list[index], index + 1);
            Dfs(curr, index + 1);
        }

        /// <summary>
        /// int valueを素因数分解し、素因数を列挙します。
        /// </summary>
        /// <param name="value">素因数分解する値</param>
        /// <returns>素因数の集合</returns>
        public static IEnumerable<int> FactorizeInt(int value)
        {
            int first = value;
            for (int i = 2; i * i < first; i++)
            {
                while (value % i == 0)
                {
                    value /= i;
                    yield return i;
                }
            }

            if (value > 1)
                yield return value;
        }

        /// <summary>
        /// long valueを素因数分解し、素因数を列挙します。
        /// </summary>
        /// <param name="value">素因数分解する値</param>
        /// <returns>素因数の集合</returns>
        public static IEnumerable<long> FactorizeLong(long value)
        {
            long first = value;
            for (long i = 2; i * i < first; i++)
            {
                while (value % i == 0)
                {
                    value /= i;
                    yield return i;
                }
            }

            if (value > 1)
                yield return value;
        }

        /// <summary>
        /// long valueを素因数分解し、素因数とその個数の連想配列を返します。
        /// </summary>
        /// <param name="value">素因数分解する値</param>
        /// <returns>素因数の連想配列</returns>
        public static Dictionary<long, int> FactorizeAsMapLong(long value)
        {
            var  dict  = new Dictionary<long, int>();
            long first = value;
            for (long i = 2; i * i < first; i++)
            {
                if (value % i > 0) continue;
                int cnt = 0;
                while (value % i == 0)
                {
                    value /= i;
                    cnt++;
                }

                dict.Add(i, cnt);
            }

            if (value > 1) dict.Add(value, 1);
            return dict;
        }

        /// <summary>
        /// int valueを素因数分解し、素因数とその個数の連想配列を返します。
        /// </summary>
        /// <param name="value">素因数分解する値</param>
        /// <returns>素因数の連想配列</returns>
        public static Dictionary<int, int> FactorizeAsMapInt(int value)
        {
            var dict  = new Dictionary<int, int>();
            int first = value;
            for (int i = 2; i * i < first; i++)
            {
                if (value % i > 0) continue;
                int cnt = 0;
                while (value % i == 0)
                {
                    value /= i;
                    cnt++;
                }

                dict.Add(i, cnt);
            }

            if (value > 1) dict.Add(value, 1);
            return dict;
        }

        /// <summary>
        /// valueの約数の個数を求めます。
        /// </summary>
        /// <param name="value">約数の個数を求める数</param>
        /// <returns>valueの約数の個数</returns>
        public static long Divisors(long value)
        {
            var fact = FactorizeAsMapLong(value);
            return fact.Select(x => x.Value + 1L).Aggregate((m, x) => m * x);
        }
    }


//=========================================================================================
// Library
//=========================================================================================


//=========================================================================================
// Debug IO
//=========================================================================================

    public partial class Program
    {
        //=========================================================================================
        // Main
        //=========================================================================================

        private readonly ConsoleInput cin;
        private readonly IConsole     cou;

        public Program(ConsoleInput cin, IConsole cou)
        {
            this.cin = cin;
            this.cou = cou;
        }

        public static void Main(string[] args)
        {
#if UTAKA_LOCAL
//#if false
            new TestCaseCheckerForAtCoder().TestProblems();
#else
            var cin = new ConsoleInput(System.Console.In);
            var console = new MyConsole();
            new Program(cin, console).Solve();
            console.Flush();
#endif
        }
    }

    public class ConsoleInput
    {
        private readonly char          _separator = ' ';
        private readonly TextReader    _stream;
        private readonly Queue<string> inputStream;

        public ConsoleInput(TextReader stream, char separator = ' ')
        {
            _separator  = separator;
            _stream     = stream;
            inputStream = new Queue<string>();
        }

        public string Read
        {
            get
            {
                if (inputStream.Count != 0)
                {
                    return inputStream.Dequeue();
                }

                var tmp = _stream.ReadLine().Split(_separator);
                for (var i = 0; i < tmp.Length; ++i)
                {
                    inputStream.Enqueue(tmp[i]);
                }

                return inputStream.Dequeue();
            }
        }

        public string ReadLine   => _stream.ReadLine();
        public int    ReadInt    => int.Parse(Read);
        public long   ReadLong   => long.Parse(Read);
        public double ReadDouble => double.Parse(Read);

        public string[] ReadStrArray(long N)
        {
            var ret = new string[N];
            for (long i = 0; i < N; ++i)
            {
                ret[i] = Read;
            }

            return ret;
        }

        public int[] ReadIntArray(long N)
        {
            var ret = new int[N];
            for (long i = 0; i < N; ++i)
            {
                ret[i] = ReadInt;
            }

            return ret;
        }

        public long[] ReadLongArray(long N)
        {
            var ret = new long[N];
            for (long i = 0; i < N; ++i)
            {
                ret[i] = ReadLong;
            }

            return ret;
        }
    }

    public interface IConsole
    {
        void Flush();
        void Write(object obj);
        void Write(string str);
        void WriteLine(object obj);
        void WriteLine(string str);
        void WriteLine();
    }

    public class MyConsole : IConsole
    {
        public MyConsole()
        {
            var sw = new StreamWriter(Console.OpenStandardOutput()) {AutoFlush = false};
            Console.SetOut(sw);
        }

        public void Flush()
        {
            Console.Out.Flush();
        }

        public void Write(object obj)
        {
            Write(obj.ToString());
        }

        public void Write(string str)
        {
            Console.Write(str);
        }

        public void WriteLine(object obj)
        {
            WriteLine(obj.ToString());
        }

        public void WriteLine(string str)
        {
            Console.WriteLine(str);
        }

        public void WriteLine()
        {
            Console.WriteLine();
        }
    }

#if UTAKA_LOCAL

    public class DebugConsole : IConsole
    {
        private readonly StringBuilder mSb;

        public DebugConsole()
        {
            mSb = new StringBuilder();
        }

        public void Flush()
        {
            // 何もしない
        }

        public void Write(object obj)
        {
            Write(obj.ToString());
        }

        public void Write(string str)
        {
            mSb.Append(str);
        }

        public void WriteLine(object obj)
        {
            WriteLine(obj.ToString());
        }

        public void WriteLine(string str)
        {
            mSb.AppendLine(str);
        }

        public void WriteLine()
        {
            mSb.AppendLine();
        }

        public string GetAllOutput()
        {
            return mSb.ToString();
        }
    }

#endif

#if UTAKA_LOCAL

    public class TestCaseCheckerForAtCoder
    {
        private string GetDirectoryPath()
        {
            var problemPart = string.IsNullOrEmpty(Program.ProblemName)
                ? ""
                : $"/{Program.ProblemName}";

            return
                $"{Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)}/AlgorithmPrac/{Program.SiteName}/{Program.ContestName}{problemPart}";
        }

        private string GetInputFilePath(int testCaseNumber)
        {
            return $"{GetDirectoryPath()}/sample-{testCaseNumber}.in";
        }

        private string GetOutputFilePath(int testCaseNumber)
        {
            return $"{GetDirectoryPath()}/sample-{testCaseNumber}.out";
        }

        public bool TestProblem(int testCaseNumber)
        {
            var inputFilePath  = GetInputFilePath(testCaseNumber);
            var outputFilePath = GetOutputFilePath(testCaseNumber);

            TextReader inputStream = new StreamReader(inputFilePath);
            var        cin         = new ConsoleInput(inputStream);

            var debugConsoleWriter = new DebugConsole();

            new Program(cin, debugConsoleWriter).Solve();

            var output = debugConsoleWriter.GetAllOutput();

            TextReader outputStream = new StreamReader(outputFilePath);
            var        outputAnswer = outputStream.ReadToEnd();

            Dbg.WriteLine(output);
            Dbg.WriteLine(outputAnswer);

            var isCorrect = output == outputAnswer;

            return isCorrect;
        }

        public void TestProblems(int targetTestCaseNumber = -1)
        {
            if (targetTestCaseNumber >= 0)
            {
                Console.WriteLine($"!!!!!!!!!!!! Check TestCase {targetTestCaseNumber} !!!!!!!!!!");
            }

            bool isSuccessAll = true;

            int testCaseNumber = 0;
            while (true)
            {
                testCaseNumber++;

                if (targetTestCaseNumber >= 0 && targetTestCaseNumber != testCaseNumber)
                {
                    continue;
                }

                var inputFileName = GetInputFilePath(testCaseNumber);
                if (!File.Exists(inputFileName))
                {
                    break;
                }

                Console.WriteLine($"TestCase {testCaseNumber} =====================================================");

                var result = TestProblem(testCaseNumber);

                if (result)
                {
                    Console.WriteLine("Success");
                }
                else
                {
                    isSuccessAll = false;
                    Console.WriteLine("Failure *****");
                }
            }

            if (isSuccessAll)
            {
                Console.WriteLine("!!!!!!!!! All Success !!!!!!!!!");
            }
        }
    }

#endif

#if UTAKA_LOCAL

    public static class Dbg
    {
        public static void WriteLine(string str)
        {
            Console.WriteLine(str);
        }

        public static void Write(string str)
        {
            Console.Write(str);
        }
    }
#else
    public static class Dbg
    {
        public static void WriteLine(string str)
        {
        }

        public static void Write(string str)
        {
        }
    }

#endif
}