Skip to content

Commit 2deb87d

Browse files
solves three diivisors
1 parent 2996881 commit 2deb87d

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -468,7 +468,7 @@
468468
| 1935 | [Maximum Number of Words You Can Type](https://leetcode.com/problems/maximum-number-of-words-you-can-type) | [![Java](assets/java.png)](src/MaximumNumberOfWordsYouCanType.java) | |
469469
| 1941 | [Check if All Characters Have Equal Number of Occurrences](https://leetcode.com/problems/check-if-all-characters-have-equal-number-of-occurrences) | [![Java](assets/java.png)](src/CheckIfAllCharactersHaveEqualNumberOfOccurrences.java) | |
470470
| 1945 | [Sum of Digits of String After Convert](https://leetcode.com/problems/sum-of-digits-of-string-after-convert) | [![Java](assets/java.png)](src/SumOfDigitsOfStringAfterConvert.java) | |
471-
| 1952 | [Three Divisors](https://leetcode.com/problems/three-divisors) | | |
471+
| 1952 | [Three Divisors](https://leetcode.com/problems/three-divisors) | [![Java](assets/java.png)](src/ThreeDivisors.java) | |
472472
| 1957 | [Delete Characters to Make Fancy String](https://leetcode.com/problems/delete-characters-to-make-fancy-string) | | |
473473
| 1961 | [Check If String Is a Prefix of Array](https://leetcode.com/problems/check-if-string-is-a-prefix-of-array) | | |
474474
| 1967 | [Number of Strings That Appear as Substrings in Word](https://leetcode.com/problems/number-of-strings-that-appear-as-substrings-in-word) | | |

src/ThreeDivisors.java

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// https://leetcode.com/problems/three-divisors
2+
// T: O(1)
3+
// S: O(1)
4+
5+
public class ThreeDivisors {
6+
private static final PrimeSieve PRIME_SIEVE = PrimeSieve.ofSize(101);
7+
8+
public boolean isThree(int n) {
9+
return isPerfectSquare(n);
10+
}
11+
12+
private boolean isPerfectSquare(int x) {
13+
int sqrt = (int) Math.sqrt(x);
14+
return sqrt * sqrt == x && PRIME_SIEVE.isPrime(sqrt);
15+
}
16+
17+
private static class PrimeSieve {
18+
final byte[] sieve;
19+
20+
private static PrimeSieve ofSize(int size) {
21+
return new PrimeSieve(size);
22+
}
23+
24+
PrimeSieve(int size) {
25+
this.sieve = new byte[size + 1];
26+
initializeSieve();
27+
}
28+
29+
public boolean isPrime(int number) {
30+
return sieve[number] == 0;
31+
}
32+
33+
private void initializeSieve() {
34+
sieve[0] = 1;
35+
sieve[1] = 1;
36+
for (int i = 2 ; i < sieve.length ; i++) {
37+
if (sieve[i] == 0) {
38+
markFactors(i);
39+
}
40+
}
41+
}
42+
43+
private void markFactors(int prime) {
44+
for (int i = prime * prime ; i < sieve.length ; i += prime) {
45+
sieve[i] = 1;
46+
}
47+
}
48+
}
49+
}

0 commit comments

Comments
 (0)