File tree Expand file tree Collapse file tree 2 files changed +51
-8
lines changed
contest/src/main/java/com/github/contest Expand file tree Collapse file tree 2 files changed +51
-8
lines changed Original file line number Diff line number Diff line change 1
1
package com.github.contest
2
2
3
3
4
- import com.github.contest.hashTable.findMissingAndRepeatedValuesProdVariant
4
+ import com.github.contest.math.closestPrimes
5
5
import java.util.TreeMap
6
6
7
7
@@ -11,12 +11,7 @@ import java.util.TreeMap
11
11
12
12
fun main () {
13
13
14
- findMissingAndRepeatedValuesProdVariant(
15
- arrayOf(
16
- intArrayOf(1 , 3 ),
17
- intArrayOf(2 , 2 )
18
- )
19
- ).also { it.printArray() }
14
+ closestPrimes(19 , 31 ).also { it.printArray() }
20
15
}
21
16
22
17
fun generateTesting () {
Original file line number Diff line number Diff line change 1
1
package com.github.contest.math
2
2
3
+ import kotlin.math.sqrt
4
+
3
5
/* *
4
6
* 1025. Divisor Game
5
7
*/
@@ -29,4 +31,50 @@ fun checkPowersOfThree(n: Int): Boolean {
29
31
fun coloredCells (n : Int ): Long = when {
30
32
n == 1 -> 1L
31
33
else -> coloredCells(n - 1 ) + 4L * (n - 1 ).toLong()
32
- }
34
+ }
35
+
36
+ /* *
37
+ * 2523. Closest Prime Numbers in Range
38
+ */
39
+
40
+
41
+ fun closestPrimes (left : Int , right : Int ): IntArray {
42
+ val primes = mutableListOf<Int >()
43
+ val isPrime = BooleanArray (right + 1 ) { true }
44
+ isPrime[0 ] = false
45
+ isPrime[1 ] = false
46
+
47
+ for (p in 2 .. sqrt(right.toDouble()).toInt()) {
48
+ if (isPrime[p]) {
49
+ for (i in p * p.. right step p) {
50
+ isPrime[i] = false
51
+ }
52
+ }
53
+ }
54
+
55
+ for (p in left.. right) {
56
+ if (isPrime[p]) {
57
+ primes.add(p)
58
+ }
59
+ }
60
+
61
+ if (primes.size < 2 ) return intArrayOf(- 1 , - 1 )
62
+
63
+ var minDiff = Int .MAX_VALUE
64
+ var result = intArrayOf(- 1 , - 1 )
65
+ for (i in 0 until primes.size - 1 ) {
66
+ val diff = primes[i + 1 ] - primes[i]
67
+ if (diff < minDiff) {
68
+ minDiff = diff
69
+ result[0 ] = primes[i]
70
+ result[1 ] = primes[i + 1 ]
71
+ }
72
+ }
73
+
74
+ return result
75
+ }
76
+
77
+ private fun isPrime (number : Int ): Boolean {
78
+ for (i in number - 1 downTo 2 ) if (number % i == 0 ) return false
79
+ return true
80
+ }
You can’t perform that action at this time.
0 commit comments