Java examples for java.lang:Math Number
Gets the sum of the divisors of a number
//package com.java2s; import java.util.*; public class Main { /**/*from ww w . ja v a 2s. co m*/ * 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; } }