Monday, August 5, 2019

isPrime, optimization 1

It is not necessary to check divisors bigger than the square root of the number.

1
2
3
4
5
6
7
8
9
bool isPrime1( int x ) {
  int limit = (int) sqrt(x);
  for( int divisor = 2; divisor <= limit; divisor++ ) {
        if( x % divisor == 0 ) { 
            return false;
        }
  }
  return true;
}

No comments:

Post a Comment