Project Euler #23: Non-abundant sums

  • + 0 comments

    c# using System; using System.Collections.Generic;

    public class Program { static List primes = new List { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 }; static List abundants = new List();

    static long Mod(long x, long mod)
    {
        return x % mod >= 0 ? x % mod : x % mod + mod;
    }
    
    static List<int> FindPrimes(int n)
    {
        for (int i = 51; i <= n; i += 2)
        {
            bool flag = false;
            foreach (int j in primes)
            {
                if (j * j > i)
                    break;
                if (i % j == 0)
                {
                    flag = true;
                    break;
                }
            }
            if (!flag)
                primes.Add(i);
        }
        return primes;
    }
    
    static bool IsAbundant(int n)
    {
        long ans = 1;
        int n_copy = n;
        foreach (int i in primes)
        {
            if (i * i > n_copy)
                break;
            if (n % i == 0)
            {
                int cnt = 0;
                while (n % i == 0)
                {
                    cnt++;
                    n /= i;
                }
                ans *= ((Power(i, cnt + 1) - 1) / (i - 1));
            }
        }
        if (n > 1)
            ans *= ((n * n - 1) / (n - 1));
        ans -= n_copy;
        return ans > n_copy;
    }
    
    static bool Solve(int n)
    {
        foreach (int i in abundants)
        {
            if (i > n / 2 + 1)
                return false;
            if (abundants.BinarySearch(n - i) >= 0)
            {
                return true;
            }
        }
        return false;
    }
    
    static long Power(long x, long y)
    {
        long ans = 1;
        while (y > 0)
        {
            if ((y & 1) == 1)
            {
                ans = ans * x;
            }
            x = x * x;
            y >>= 1;
        }
        return ans;
    }
    
    public static void Main(string[] args)
    {
        primes.Capacity = 39;
        FindPrimes(168);
        abundants.Capacity = 25053;
        for (int i = 2; i <= 28123; i++)
        {
            if (IsAbundant(i))
                abundants.Add(i);
        }
    
        int t;
        string input = Console.ReadLine();
        if (input != null)
        {
            t = int.Parse(input);
            while (t-- > 0)
            {
                string line = Console.ReadLine();
                if (line != null)
                {
                    int n = int.Parse(line);
                    if (n > 28123)
                    {
                        Console.WriteLine("YES");
                        continue;
                    }
                    if (Solve(n))
                        Console.WriteLine("YES");
                    else
                        Console.WriteLine("NO");
                }
            }
        }
    }
    

    }