Compute greatest common divisor to prevent unnecessary integer overflow.

Fixes boost trac tickets #9662, #9778.