The problem statement can be found here.
It is possible to show that the square root of two can be expressed as an infinite continued fraction:
By expanding this for the first four iterations, we get:
def solution(N):den = 1num = 1den_dig = 1num_dig = 1count = 0for i in range(0, N):num = num + 2* denden = num - denif num >= num_dig:num_dig = num_dig * 10if den >= den_dig:den_dig = den_dig * 10if num_dig > den_dig:count += 1print("Count:", count)N = 1000solution(N)
The problem is quite simple. All we have to do is generate the infinite fraction for the number of iterations specified (in this case, a ) and return the number of continuous fractions where the number of digits of the numerator is greater than the number of digits in the denominator.
The first thing to notice is the pattern between the numerator and the denominator that will help us generate the next fractions.
If you look closely at the fractions you will notice the following pattern in the numerator and the denominators:
,
,
where represents the numerator and is the denominator in a particular iteration.
Now we need a way to calculate the number of digits in the numbers. The brute force approach would take the of the number, and the result gives you the number of digits. However, taking the is a very computationally heavy operation.
A faster method to keep track of the number of digits is to have a counter variable initialized to and to increase the variable’s value by multiplying it by each time the number goes up a digit. So, for example, if our number is within and inclusive, our counter variable will store the value , indicating that the number is less than and hence has digits.
In our code, we have two variables, num_dig
and den_dig
, that serve this purpose.
Whenever the value of num_dig
exceeds the value of den_dig
, we know that the numerator has a greater number of digits than the denominator, and we can increase the count.
Free Resources