Project Euler #12: Highly divisible triangular number

  • + 0 comments

    Test case 6 & 7 fails

    import java.io.*;
    import java.util.*;
    import java.text.*;
    import java.math.*;
    import java.util.regex.*;
    
    public class Solution {
    public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int queries = scanner.nextInt();
            for (int i = 0; i < queries; i++) {
                int n = scanner.nextInt();
                System.out.println(findTriangleNumberWithDivisors(n));
            }
            scanner.close();
        }
    
        private static long findTriangleNumberWithDivisors(int n) {
            int maxDivisors = 0;
            long result = 0;
            int currentNumber = 1;
    
            while (true) {
                long triangularNumber = calculateTriangularNumber(currentNumber);
                int divisors = countDivisors(triangularNumber);
                if (divisors > maxDivisors) {
                    maxDivisors = divisors;
                    result = triangularNumber;
                }
                if (maxDivisors > n) {
                    break;
                }
                currentNumber++;
            }
            return result;
        }
    
        private static long calculateTriangularNumber(int n) {
            return n * (n + 1) / 2;
        }
    
        private static int countDivisors(long number) {
            int count = 0;
            for (int i = 1; i <= Math.sqrt(Double.valueOf(number)); i++) { // Use Math.sqrt(double) instead of Math.sqrt(long)
                if (number % i == 0) {
                    if (number / i == i) {
                        count++;
                    } else {
                        count += 2;
                    }
    
                }
            }
            return count;
        }
    }
    

    `