From b5fdefc515b12ea6df4337ebaf35d2037cfd665e Mon Sep 17 00:00:00 2001 From: renzozuk Date: Wed, 12 Jun 2024 16:59:07 -0300 Subject: [PATCH] Feat: Perfect number algorithm --- .../algorithms/math/PerfectNumber.java | 18 +++++++++ .../algorithms/math/PerfectNumberTest.java | 39 +++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 src/main/java/com/williamfiset/algorithms/math/PerfectNumber.java create mode 100644 src/test/java/com/williamfiset/algorithms/math/PerfectNumberTest.java diff --git a/src/main/java/com/williamfiset/algorithms/math/PerfectNumber.java b/src/main/java/com/williamfiset/algorithms/math/PerfectNumber.java new file mode 100644 index 000000000..fcf1c47bb --- /dev/null +++ b/src/main/java/com/williamfiset/algorithms/math/PerfectNumber.java @@ -0,0 +1,18 @@ +package com.williamfiset.algorithms.math; + +import java.util.stream.IntStream; +import java.util.stream.LongStream; + +public class PerfectNumber { + public static boolean isPerfect(int n) { + if(n <= 1) return false; + + return IntStream.range(1, n / 2 + 1).filter(i -> n % i == 0).sum() == n; + } + + public static boolean isPerfect(long n) { + if(n <= 1L) return false; + + return LongStream.range(1, n / 2 + 1).filter(i -> n % i == 0).sum() == n; + } +} diff --git a/src/test/java/com/williamfiset/algorithms/math/PerfectNumberTest.java b/src/test/java/com/williamfiset/algorithms/math/PerfectNumberTest.java new file mode 100644 index 000000000..3ddf55941 --- /dev/null +++ b/src/test/java/com/williamfiset/algorithms/math/PerfectNumberTest.java @@ -0,0 +1,39 @@ +package com.williamfiset.algorithms.math; + +import org.junit.jupiter.api.Test; + +import java.util.Random; + +import static org.junit.jupiter.api.Assertions.*; +import static com.williamfiset.algorithms.math.PerfectNumber.isPerfect; + +class PerfectNumberTest { + private final Random random = new Random(); + + @Test + void testIsPerfect() { + assertFalse(isPerfect(random.nextInt(Integer.MIN_VALUE, 6))); + assertFalse(isPerfect(random.nextLong(Long.MIN_VALUE, 6L))); + + assertTrue(isPerfect(6)); + assertTrue(isPerfect(6L)); + + assertFalse(isPerfect(random.nextInt(7, 28))); + assertFalse(isPerfect(random.nextLong(7L, 28L))); + + assertTrue(isPerfect(28)); + assertTrue(isPerfect(28L)); + + assertFalse(isPerfect(random.nextInt(29, 8128))); + assertFalse(isPerfect(random.nextLong(29L, 8128L))); + + assertTrue(isPerfect(8128)); + assertTrue(isPerfect(8128L)); + + assertFalse(isPerfect(random.nextInt(8129, 33550336))); + assertFalse(isPerfect(random.nextLong(8129L, 33550336L))); + + assertTrue(isPerfect(33550336)); + assertTrue(isPerfect(33550336L)); + } +} \ No newline at end of file