Created PerfectNumberTest.java & Added function in PerfectNumber.java (#3751)

* Added function in PerfectNumber.java

Added isPerfectNumber2() in PerfectNumber.java

* Created PerfectNumberTest.java

* fixed isPerfectNumber()

fixed bug in isPerfectNumber() for negative numbers

* fixed typo

Co-authored-by: Debasish Biswas <debasishbsws.abc@gmail.com>
This commit is contained in:
Taranjeet Singh Kalsi 2022-11-01 11:52:56 +05:30 committed by GitHub
parent 5864f3296f
commit d418bbd1cf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 57 additions and 10 deletions

View File

@ -6,20 +6,10 @@ package com.thealgorithms.maths;
* has divisors 1, 2 and 3 (excluding itself), and 1 + 2 + 3 = 6, so 6 is a
* perfect number.
*
* <p>
* link:https://en.wikipedia.org/wiki/Perfect_number
*/
public class PerfectNumber {
public static void main(String[] args) {
assert isPerfectNumber(6);
/* 1 + 2 + 3 == 6 */
assert !isPerfectNumber(8);
/* 1 + 2 + 4 != 8 */
assert isPerfectNumber(28);
/* 1 + 2 + 4 + 7 + 14 == 28 */
}
/**
* Check if {@code number} is perfect number or not
*
@ -27,6 +17,8 @@ public class PerfectNumber {
* @return {@code true} if {@code number} is perfect number, otherwise false
*/
public static boolean isPerfectNumber(int number) {
if (number <= 0)
return false;
int sum = 0;
/* sum of its positive divisors */
for (int i = 1; i < number; ++i) {
@ -36,4 +28,38 @@ public class PerfectNumber {
}
return sum == number;
}
/**
* Check if {@code n} is perfect number or not
*
* @param n the number
* @return {@code true} if {@code number} is perfect number, otherwise false
*/
public static boolean isPerfectNumber2(int n) {
if (n <= 0)
return false;
int sum = 1;
double root = Math.sqrt(n);
/*
* We can get the factors after the root by dividing number by its factors
* before the root.
* Ex- Factors of 100 are 1, 2, 4, 5, 10, 20, 25, 50 and 100.
* Root of 100 is 10. So factors before 10 are 1, 2, 4 and 5.
* Now by dividing 100 by each factor before 10 we get:
* 100/1 = 100, 100/2 = 50, 100/4 = 25 and 100/5 = 20
* So we get 100, 50, 25 and 20 which are factors of 100 after 10
*/
for (int i = 2; i <= root; i++) {
if (n % i == 0) {
sum += i + n / i;
}
}
// if n is a perfect square then its root was added twice in above loop, so subtracting root from sum
if (root == (int) root)
sum -= root;
return sum == n;
}
}

View File

@ -0,0 +1,21 @@
package com.thealgorithms.maths;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class PerfectNumberTest {
@Test
public void perfectNumber() {
int trueTestCases[] = { 6, 28, 496, 8128, 33550336 };
int falseTestCases[] = { -6, 0, 1, 9, 123 };
for (Integer n : trueTestCases) {
assertTrue(PerfectNumber.isPerfectNumber(n));
assertTrue(PerfectNumber.isPerfectNumber2(n));
}
for (Integer n : falseTestCases) {
assertFalse(PerfectNumber.isPerfectNumber(n));
assertFalse(PerfectNumber.isPerfectNumber2(n));
}
}
}