Square root convergents
It is possible to show that the square root of two can be expressed as an infinite continued fraction.
√ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...
By expanding this for the first four iterations, we get:
1 + 1/2 = 3/2 = 1.5
1 + 1/(2 + 1/2) = 7/5 = 1.4
1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666...
1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379...
The next three expansions are 99/70, 239/169, and 577/408, but the eighth expansion, 1393/985, is the first example where the number of digits in the numerator exceeds the number of digits in the denominator.
In the first one-thousand expansions, how many fractions contain a numerator with more digits than denominator?
√ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...
By expanding this for the first four iterations, we get:
1 + 1/2 = 3/2 = 1.5
1 + 1/(2 + 1/2) = 7/5 = 1.4
1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666...
1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379...
The next three expansions are 99/70, 239/169, and 577/408, but the eighth expansion, 1393/985, is the first example where the number of digits in the numerator exceeds the number of digits in the denominator.
In the first one-thousand expansions, how many fractions contain a numerator with more digits than denominator?
Before we start with the solution, have a look at the following links:
You can also have a look at Wikipedia Continued fraction if you want.
According to the links, if p/q is is the first convergent then the next convergent can be written as (p+2q)/(p+q).
So simply we will start with 1/1 where p = 1 and q = 1 and iterate 1000 times and find how many times the length of p is greater than q.
Summary
This problem is again simple. I am satisfied with the execution time and haven't tried to optimize the code. I also liked the clean and clear solution I have written. One can still optimize the code.Please excuse and correct me if my grammar is wrong or in an ambiguous way.
Comment in the comment box below if you have any doubt or didn't understand anything. I will be glad to help you.
Please do comment in the comment box below if you have found any typo or have a different solution or a better program or have a suggestion. I will be very happy to view each of them.
You can also contact me.
Thank you. Have a nice day😃!