How to minimize $f(x)$ with the constraint that $x$ is an integer? I would like to find the integer x that minimizes a function. That is:
$$
x_{min} = \min_{x \in \mathbb{Z}}{(n - e^x)^2}
$$
The goal is to write a program that computes the integer $x$ such that $e^x$ is closest to $n$, preferably avoiding conditionals.
Without the integer constraint, obviously $x_{min} = \ln{n}$, but how to go about this with the integer constraint? 

The fact that the minimum is squared is irrelevant, if you take the absolute value instead. Therefore $$x_{min}=\min_{x\in Z}{|n-e^x|}$$
If x werent constrained to the integers, x would equal as you pointed out ln(n), but since it is constrained to integers, to find $x_{min}$, take $\min(e^{Floor(ln(n))},e^{Ceil(ln(n))})$ The minimum between those two will be your answer.
