Project Euler #23: Non-abundant sums

  • + 0 comments

    JavaCode

    import java.util.Scanner;
    
    public class Solution {
            public static int sumOfDivisors(int n) {
            int sum = 1; 
            int sqrt = (int) Math.sqrt(n);
            
            for (int i = 2; i <= sqrt; i++) {
                if (n % i == 0) {
                    if (i == n / i) {
                        sum += i; 
                    } else {
                        sum += i + (n / i);
                    }
                }
            }
            
            return sum;
        }
    
        public static void main(String[] args) {
            Scanner s = new Scanner(System.in);
            int testcase = s.nextInt(); 
    
            while (testcase-- > 0) {
                int n = s.nextInt(); 
                boolean[] isAbundant = new boolean[n + 1];
                for (int i = 1; i <= n; i++) {
                    if (sumOfDivisors(i) > i) {
                        isAbundant[i] = true;
                    }
                }
                
                boolean canBeExpressed = false;
                for (int i = 1; i <= n / 2; i++) {
                    if (isAbundant[i] && isAbundant[n - i]) {
                        canBeExpressed = true;
                        break;
                    }
                }
                
                if (canBeExpressed) {
                    System.out.println("YES");
                } else {
                    System.out.println("NO");
                }
            }
            
            s.close();
        }
    }