Last active
August 29, 2015 14:05
-
-
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?"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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