> so in order to fix my code I should add
1 2
|
> if( number%2 == 0 ) return false ;
> const int ub_root = std::sqrt(number) + 1.5 ;
|
and
1 2
|
> for( int divisor = 3 ; divisor < ub_root ; divisor += 2 )
> if( number%divisor == 0 ) return false ; // evenly divisible; not prime
|
> or do i still miss something?
It is not a "fix"; it makes the trial division faster.
For instance to check if 156 is a prime number,
instead of performing trial division by every number 2, 3, 4, 5, 6 .... 152, 153, 154, 155
now we do that only for the numbers 3, 5, 7, 9, 11
The even divisors were already taken care of by checking if 156 was even,
and the square root of 156 is 12.xxx, so we do not need to check divisibility by numbers above 13
ie. if
156 == a * b, and
a is greater than or equal to 13, then
b must be less than 13.
> I don't understand why do you add + 1.5
When a floating point number is narrowed to an integer, the rounding is towards zero.
If the number is, say, 169,
std::sqrt(169) may return 12.9999999999 (floating point computations are not exact).
A +0.5 would ensure that we get 13 as the value when we narrow it to an integer.
Another +1.0 is merely to enable us to write the loop as canonical loop
(write the loop condition as
divisor < ub_root instead of
divisor <= root)