Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,844 questions

51,765 answers

573 users

How to check if a number can be made prime by deleting a single digit in Kotlin

1 Answer

0 votes
fun removeDigit(n: Int, index: Int): Int {
    val s = n.toString()
    val newStr = s.removeRange(index, index + 1)
    
    return newStr.toInt()
}

fun isPrime(n: Int): Boolean {
    if (n < 2) return false
    if (n % 2 == 0) return n == 2

    val limit = kotlin.math.sqrt(n.toDouble()).toInt()
    for (i in 3..limit step 2) {
        if (n % i == 0) return false
    }
    
    return true
}

fun canBecomePrimeByDeletingOneDigit(n: Int): Int? {
    val s = n.toString()

    for (i in s.indices) {
        val candidate = removeDigit(n, i)
        if (isPrime(candidate)) {
            return candidate
        }
    }
    
    return null
}

fun main() {
    val n = 78919
    val result = canBecomePrimeByDeletingOneDigit(n)

    if (result != null) {
        println("yes number = $result")
    } else {
        println("no prime can be formed")
    }
}




/*
run:

yes number = 7919

*/


 



answered Jan 7 by avibootz

Related questions

...