-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPerfectNumber.java
More file actions
54 lines (39 loc) · 2.13 KB
/
PerfectNumber.java
File metadata and controls
54 lines (39 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/*********************************************************************************************************************
Perfect Number
==============
What is the perfect number?
A perfect number is a positive integer which is equal to the sum of its proper positive divisors.
Proper positive divisors are positive integers that fully divide the perfect number without leaving a remainder and exclude the perfect number itself.
For example, take the number 6:
Its proper divisors are 1, 2, and 3 (since 6 is the value of the perfect number, it is excluded), and the sum of its proper divisors is 1 + 2 + 3 = 6.
Therefore, 6 is a perfect number (as well as the first perfect number).
Write a method named isPerfectNumber with one parameter of type int named number.
If number is < 1, the method should return false.
The method must calculate if the number is perfect. If the number is perfect, the method should return true; otherwise, it should return false.
EXAMPLE INPUT/OUTPUT:
isPerfectNumber(6); should return true since its proper divisors are 1, 2, 3 and the sum is 1 + 2 + 3 = 6
isPerfectNumber(28); should return true since its proper divisors are 1, 2, 4, 7, 14 and the sum is 1 + 2 + 4 + 7 + 14 = 28
isPerfectNumber(5); should return false since its only proper divisor is 1 and the sum is 1 not 5
isPerfectNumber(-1); should return false since the number is < 1
HINT: Use a while or for loop.
HINT: Use the remainder operator.
NOTE: The method isPerfectNumber should be defined as public static like we have been doing so far in the course.
NOTE: Do not add a main method to the solution code.
**********************************************************************************************************************/
public class PerfectNumber {
public static boolean isPerfectNumber(int number)
{
if (number>=1)
{
int sum=0;
for (int i=1;i<=number/2;i++)
{
if (number%i==0)
sum+=i;
}
return (sum==number);
}
else
return false;
}
}