An O(log n) algorithm for computing periodic continued fractions and its applications