Skip to content

Commit

Permalink
Merge pull request TheAlgorithms#1016 from shellhub/feature-1
Browse files Browse the repository at this point in the history
perfect number
  • Loading branch information
yanglbme authored Oct 11, 2019
2 parents d609652 + 58b9f0b commit f6ca5e3
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions Maths/PerfectNumber.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package Maths;

/**
* In number theory, a perfect number is a positive integer that is equal to the sum of
* its positive divisors, excluding the number itself. For instance, 6 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
* </p>
*/
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
*
* @param number the number
* @return {@code true} if {@code number} is perfect number, otherwise false
*/
public static boolean isPerfectNumber(int number) {
int sum = 0; /* sum of its positive divisors */
for (int i = 1; i < number; ++i) {
if (number % i == 0) {
sum += i;
}
}
return sum == number;
}
}

0 comments on commit f6ca5e3

Please sign in to comment.