Looking for something similar to Python's bisect_right

Zeke lcarsos at lcarsos.com
Wed Oct 30 11:56:41 PDT 2013


On Wednesday, 30 October 2013 at 14:17:22 UTC, qznc wrote:
> Why do you want to find the exact prime first? Just check 
> against sqrt(num) in the loop.
>
> auto upper = cast(ulong)sqrt(cast(double)num)) + 1;
> foreach(ulong prime; primes) {
>   if (prime > upper) return true;
>   if (num % prime == 0) return false;
> }
> assert (false); // should be unreachable?

Because having a branch inside the foreach causes a branch 
prediction error when you've found a prime number. Simply 
iterating up to the sqrt and then terminating the loop has no 
branch prediction error. Try it for yourself.


More information about the Digitalmars-d-learn mailing list