Project Euler #12: Highly divisible triangular number

  • + 0 comments

    BY TANUSHREE SARKAR

    import java.io.*;
    import java.util.*;
    
    public class Solution {
    
        public static void main(String[] args) {
            int[] primes = new int[1000];
            primes[0] = 2;
            primes[1] = 3;
            primes[2] = 5;
            primes[3] = 7;
            int count1 = 4;
            int num = 9;
    
            while (num <= 1000000) {
                boolean isPrime = true;
                for (int i = 0; i < count1; i++) {
                    if (num % primes[i] == 0) {
                        isPrime = false;
                        break;
                    } else if (primes[i] > (num / 2)) {
                        break;
                    }
                }
                if (isPrime) {
                    primes[count1] = num;
                    count1++;
                    if (count1 == 1000) {
                        break;
                    }
                }
                num += 2;
            }
    
            Scanner in = new Scanner(System.in);
            int t = in.nextInt();
            for (int a0 = 0; a0 < t; a0++) {
                long n = in.nextLong();
    
                int j = 2;
                long result = 1;
                long sum = 1;
                int count2 = 1;
    
                while (true) {
                    sum += j;
                    long temp = sum;
    
                    for (int k = 0; k < 1000; k++) {
                        count2 = 1;
                        while (true) {
                            if (temp % primes[k] == 0) {
                                temp /= primes[k];
                                count2++;
                            } else {
                                break;
                            }
                        }
                        result *= count2;
                        if (temp == 1) {
                            break;
                        }
                    }
                    if (result > n) {
                        break;
                    } else {
                        result = 1;
                    }
                    j++;
                }
                System.out.println(sum);
            }
        }
    }