FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
leetcode/java/507_Perfect_Number.java at master · jakehoare/leetcode · GitHub
jakehoare
/
leetcode
Public
Notifications
You must be signed in to change notification settings
Fork
30
Star
51
Code
Issues
0
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
leetcode
/
java
/
507_Perfect_Number.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
29 lines (23 loc) · 883 Bytes
Breadcrumbs
leetcode
/
java
/
507_Perfect_Number.java
Copy path
File metadata and controls
29 lines (23 loc) · 883 Bytes
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
/*
https://leetcode.com/problems/perfect-number/
We define the Perfect Number is a positive integer that is equal to the sum of all its positive divisors except itself.
Now, given an integer n, write a function that returns true when it is a perfect number and false when it is not.
Try all divisors from 2 to sqrt(n).
Time - O(sqrt(n))
Space - O(1)
*/
class
Solution
{
public
boolean
checkPerfectNumber
(
int
num
) {
if
(
num
==
1
)
// no divisors apart from self
return
false
;
int
sumDivisors
=
1
;
int
maxDivisor
= (
int
)
Math
.
sqrt
(
num
);
for
(
int
i
=
2
;
i
<=
maxDivisor
; ++
i
) {
if
(
num
%
i
==
0
)
sumDivisors
+=
i
+
num
/
i
;
}
if
(
maxDivisor
*
maxDivisor
==
num
)
// double-counted if num is a square
sumDivisors
-=
maxDivisor
;
return
sumDivisors
==
num
;
}
}
Back
|
FazBrowse Home
|
New Git URL