From d2aca8d88f49a740b618a819634e829373bc6bf6 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Tue, 12 Nov 2024 00:03:52 +0100 Subject: [PATCH] =?UTF-8?q?kt:=20add=20=C2=AB2601.=20Prime=20Subtraction?= =?UTF-8?q?=20Operation=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/prime-subtraction-operation/ Signed-off-by: Matej Focko --- kt/prime-subtraction-operation.kt | 36 +++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 kt/prime-subtraction-operation.kt diff --git a/kt/prime-subtraction-operation.kt b/kt/prime-subtraction-operation.kt new file mode 100644 index 0000000..66e674f --- /dev/null +++ b/kt/prime-subtraction-operation.kt @@ -0,0 +1,36 @@ +class Solution { + private fun getPrimes(nums: IntArray): BooleanArray { + val primes = BooleanArray(1 + nums.max()) { true } + primes[1] = false + + (2..sqrt(primes.size.toDouble()).toInt()) + .asSequence() + .filter { primes[it] } + .forEach { i -> + (i * i.. + primes[j] = false + } + } + + return primes + } + + fun primeSubOperation(nums: IntArray): Boolean { + val primes = getPrimes(nums) + + var (current, i) = 1 to 0 + while (i < nums.size) { + val difference = nums[i] - current + if (difference < 0) { + return false + } + + if (primes[difference] || difference == 0) { + i += 1 + } + current += 1 + } + + return true + } +}