Skip to content

Instantly share code, notes, and snippets.

@marchof
Last active August 29, 2015 14:05
Show Gist options
  • Save marchof/81bcfa0c2ab5304ae83a to your computer and use it in GitHub Desktop.
Save marchof/81bcfa0c2ab5304ae83a to your computer and use it in GitHub Desktop.
Puzzle by Dr Wolfgang Laun: "Which is the smallest non-negative integer value that cannot be stored without loss of precision in a double?"
import java.util.function.LongPredicate;
public class LowestIntegerWithLossInDouble {
static long findFirst(long lower, long upper, LongPredicate predicate) {
while (lower < upper) {
long mid = lower + (upper - lower) / 2;
if (predicate.test(mid)) {
upper = mid;
} else {
lower = mid + 1;
}
}
return lower;
}
static boolean hasLoss(long i) {
return i != (long) (double) i;
}
public static void main(String[] args) {
System.out.println(findFirst(0, Long.MAX_VALUE, LowestIntegerWithLossInDouble::hasLoss));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment