[Solved] Rephrase pascal code to c++ so it can work as efficient as possible


Restate problem:
1) Compute F = largest proper factor of X
2) Output X-F

Instead of directly searching for the largest proper factor, apply three trivial optimizations (maybe something more advanced will be needed, but first see if three trivial optimizations are enough).

A) Find S = smallest factor of X greater than 1. Output X-(X/S)
B) Special case for prime
C) Special case for even

int largest_proper_factor(int X)
{
   if ( X % 2 == 0 ) return X/2;  // Optimize even

   // Note the add of .5 is only needed for non compliant sqrt version that
   // might return a tiny fraction less than the exact answer.
   int last = (int)(.5 + std::sqrt( (double) X )) );

   for ( int i=3; i<=last; i+=2 ) // big savings here because even was optimized earlier
   {
      if ( X % i == 0 ) return X/i;
   }
   return 1;  // special case for prime
}

solved Rephrase pascal code to c++ so it can work as efficient as possible