calculates a^x mod p in logarithmic time