Project Euler #57: Square root convergents

  • + 0 comments

    JAva Code

    import java.io.*;
    import java.util.*;
    import java.math.*;
    
    public class Solution {
    
        public static void main(String[] args) {
            /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
            Scanner scanner = new Scanner(System.in);
            int N = scanner.nextInt();
            scanner.close();
    
            List<Integer> iterations = new ArrayList<>();
            BigInteger numerator = BigInteger.valueOf(3);
            BigInteger denominator = BigInteger.valueOf(2);
    
            for (int i = 2; i <= N; i++) {
                BigInteger newNumerator = numerator.add(denominator.multiply(BigInteger.valueOf(2)));
                BigInteger newDenominator = numerator.add(denominator);
    
                if (newNumerator.toString().length() > newDenominator.toString().length()) {
                    iterations.add(i);
                }
    
                numerator = newNumerator;
                denominator = newDenominator;
            }
    
            for (int iteration : iterations) {
                System.out.println(iteration);
            }
        }
    }