Project Euler #12: Highly divisible triangular number

  • + 0 comments

    c# using System;

    namespace Solution { class Program { 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;
    
            int i = 0;
    
            while (num <= 1000000 && count1 < primes.Length) // Ensure count1 doesn't exceed array bounds
            {
                for (i = 0; i < count1; i++)
                {
                    if (num % primes[i] == 0)
                    {
                        break;
                    }
                    else if (primes[i] > (num / 2))
                    {
                        primes[count1] = num;
                        count1++;
    
                        if (count1 == 1000)
                        {
                            break;
                        }
                        break;
                    }
                }
    
                if (i == count1)
                {
                    primes[count1] = num;
                    count1++;
    
                    if (count1 == 1000)
                    {
                        break;
                    }
                }
    
                num += 2;
            }
    
            int t = Convert.ToInt32(Console.ReadLine());
            for (int a0 = 0; a0 < t; a0++)
            {
                long n = Convert.ToInt64(Console.ReadLine());
    
                int j = 2;
                long result = 1;
                long sum = 1;
                int count2 = 1;
    
                while (true)
                {
                    sum += j;
                    long temp = sum;
    
                    for (int k = 0; k < count1; k++) // Iterate up to count1
                    {
                        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++;
                }
    
                Console.WriteLine(sum);
            }
        }
    }
    

    }