Solution to Project Euler Problem 57: 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 + ...)))). By expanding this for the first four iterations, we get: 1 + 1/2 = 3/2 = 1.5, 1 + 1/(1 + 1/2) = 7/5 = 1.4, 1 + (1/(2 + 1/(2 + 1/2))) = 1.41666... 1 + (1/(2 + 1/(2 + 1/(2 + 1/2)))) = 1.41379... The next three expansions are 99/70, 239/269, 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 the denominator?
Updated: Jan. 28, 2021 — Training Time: 2 minutes
Overseen by: Archangel Macsika
Topic: Project Euler Problem 57: Square root convergents.
Difficulty: Easy.
Objective: 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 + ...))))
By expanding this for the first four iterations, we get:
1 + 1/2 = 3/2 = 1.5
1 + 1/(1 + 1/2) = 7/5 = 1.4
1 + (1/(2 + 1/(2 + 1/2))) = 1.41666...
1 + (1/(2 + 1/(2 + 1/(2 + 1/2)))) = 1.41379... The next three expansions are 99/70, 239/269, 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 the denominator?
Input: None.
Expected Output: 153.
Sikademy Solution in Java Programming Language
package sikademy;
/**
*
* @author Archangel Macsika
* Copyright (c) Sikademy. All rights reserved
*/
import java.math.BigInteger;
public class SikademyEulerSolution {
private static final int LIMIT = 1000;
public String run() {
BigInteger n = BigInteger.ZERO;
BigInteger d = BigInteger.ONE;
int count = 0;
for (int i = 0; i < LIMIT; i++) {
BigInteger temp = d.multiply(BigInteger.valueOf(2)).add(n);
n = d;
d = temp;
if (n.add(d).toString().length() > d.toString().length())
count++;
}
return Integer.toString(count);
}
public static void main(String[] args) {
SikademyEulerSolution solution = new SikademyEulerSolution();
System.out.println(solution.run());
}
}
Sikademy Solution in Python Programming Language
#
# @author Archangel Macsika
# Copyright (c) Sikademy. All rights reserved.
#
def compute():
LIMIT = 1000
ans = 0
numer = 0
denom = 1
for _ in range(LIMIT):
numer, denom = denom, denom * 2 + numer
# Now numer/denom is the i'th (0-based) continued fraction approximation of sqrt(2) - 1
if len(str(numer + denom)) > len(str(denom)):
ans += 1
return str(ans)
if __name__ == "__main__":
print(compute())