Excessively Abundant Numbers in Java

The challenge

An abundant number or excessive number is a number for which the sum of its proper divisors is greater than the number itself.

The integer 12 is the first abundant number. Its proper divisors are 1, 2, 3, 4 and 6 for a total of 16 (> 12).

Derive function abundantNumber(num)/abundant_number(num) which returns true/True/.true. if num is abundant, false/False/.false. if not.

The solution in Java code

Option 1 (using IntStream):

import java.util.stream.IntStream; public class Solution { public static boolean abundantNumber(int num) { return num < IntStream.rangeClosed(1, num/2).filter(i -> num % i == 0).sum(); } }
Code language: Java (java)

Option 2 (without using streams):

public class Solution { public static boolean abundantNumber(int num) { int total = 0; for(int i=1;i<(num/2)+1;i++){ if(num%i==0) total += i; } return total > num; } }
Code language: Java (java)

Test cases to validate our Java solution

import org.junit.Test; import static org.junit.Assert.assertEquals; import java.util.Random; public class AbundantTests { @Test public void testAbundant() { assertEquals("Should work with 12", true, Solution.abundantNumber(12)); assertEquals("Should work with 18", true, Solution.abundantNumber(18)); assertEquals("Should work with 120", true, Solution.abundantNumber(120)); assertEquals("Should work with 5830", true, Solution.abundantNumber(5830)); assertEquals("Should work with 11410", true, Solution.abundantNumber(11410)); assertEquals("Should work with 11690", true, Solution.abundantNumber(11690)); } @Test public void testNonAbundant() { assertEquals("Should return false with 37", false, Solution.abundantNumber(37)); assertEquals("Should return false with 77", false, Solution.abundantNumber(77)); assertEquals("Should return false with 118", false, Solution.abundantNumber(118)); assertEquals("Should return false with 14771", false, Solution.abundantNumber(14771)); } private static boolean abundantNumber(int num) { int sum = 0; for (int i = 1; i <= Math.sqrt(num); i++) { if (num % i == 0) { sum += i; if (i != num / i) { sum += num / i; } } } return (sum - num > num); } @Test public void testRandomNumbers() { Random random = new Random(); for(int i = 0; i < 40; i++) { int num = random.nextInt(99000) + 1000; assertEquals("Failed on random test: " + num, abundantNumber(num), Solution.abundantNumber(num)); } } }
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments