Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: Perfect number algorithm #417

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/main/java/com/williamfiset/algorithms/math/PerfectNumber.java
Original file line number Diff line number Diff line change
@@ -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;
}
}
Original file line number Diff line number Diff line change
@@ -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));

renzozuk marked this conversation as resolved.
Show resolved Hide resolved
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));
}
}