Gets if a number is amicable A number is amicable iff a!=b and the sum of the divisors of a == b and then sum of the divisors of b == a - Java java.lang

Java examples for java.lang:Math Number

Description

Gets if a number is amicable A number is amicable iff a!=b and the sum of the divisors of a == b and then sum of the divisors of b == a

Demo Code


//package com.java2s;

import java.util.*;

public class Main {
    /**/*from  w w w.j av  a 2 s . co  m*/
     * Gets if a number is amicable
     * <em>
     * <p>A number is amicable iff a!=b and the sum of the divisors of a == b and then sum of the </p>
     * <p>divisors of b == a</p>
     * </em>
     *
     * @param num
     * @return
     */
    public static boolean isAmicableNumber(long num) {
        long amicableNum = getSumOfDivisors(num);
        if (amicableNum == num)
            return false;
        return getSumOfDivisors(amicableNum) == num;
    }

    /**
     * Gets the sum of the divisors of a number (<em>seems common in Project Euler problems</em>)
     *
     * @param num The number to get the sum of divisors for
     * @return The sum of divisors
     */
    public static long getSumOfDivisors(long num) {
        List<Long> divisors = getDivisors(num);
        long sum = 0;
        for (Long l : divisors) {
            sum += l;
        }
        return sum;
    }

    /**
     * Gets a list of divisors of a number
     *
     * @param num The number to get divisors for
     * @return The list of divisors
     */
    public static List<Long> getDivisors(long num) {
        List<Long> nums = new ArrayList<Long>();
        for (long i = 1; i <= Math.sqrt(num); i++) {
            if (num % i == 0) {
                if (i == Math.sqrt(num) || i == 1) {
                    nums.add(i);
                } else {
                    nums.add(i);
                    nums.add(num / i);
                }
            }
        }
        return nums;
    }
}

Related Tutorials