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 Swift

2 Answers

0 votes
import Foundation

func removeDigit(_ n: Int, at index: Int) -> Int {
    var s = String(n)
    let removeIndex = s.index(s.startIndex, offsetBy: index)
    s.remove(at: removeIndex)
    
    return Int(s)!
}

func isPrime(_ n: Int) -> Bool {
    if n < 2 { return false }
    if n % 2 == 0 { return n == 2 }

    let limit = Int(Double(n).squareRoot())
    var i = 3
    while i <= limit {
        if n % i == 0 { return false }
        i += 2
    }
    
    return true
}

func primeByDeletingOneDigit(_ n: Int) -> Int? {
    let digits = Array(String(n))

    for i in digits.indices {
        let candidate = removeDigit(n, at: i)
        if isPrime(candidate) {
            return candidate
        }
    }
    
    return nil
}

let n = 78919
if let result = primeByDeletingOneDigit(n) {
    print("yes number = \(result)")
} else {
    print("no prime can be formed")
}




/*
run:

yes number = 7919

*/

 



answered Jan 7 by avibootz
0 votes
import Foundation

// Helper function to check if a number is prime
func isPrime(_ n: Int) -> Bool {
    if n <= 1 { return false }
    if n <= 3 { return true }
    if n % 2 == 0 || n % 3 == 0 { return false }
    
    var i = 5
    while i * i <= n {
        if n % i == 0 || n % (i + 2) == 0 {
            return false
        }
        i += 6
    }
    
    return true
}

// Main function to check if deleting one digit makes the number prime
func canBePrimeByDeletingOneDigit(_ number: Int) -> Bool {
    let strNum = String(number)
    
    // Iterate through each digit position
    for i in 0..<strNum.count {
        var tempStr = strNum
        let index = tempStr.index(tempStr.startIndex, offsetBy: i)
        
        // Remove the digit at current index
        tempStr.remove(at: index)
        
        // Convert back to Int and check if it's prime
        if let newNum = Int(tempStr), isPrime(newNum) {
            return true
        }
    }
    
    return false
}

let n = 78919
if canBePrimeByDeletingOneDigit(n) {
    print("Yes, \(n) can be prime after deleting one digit.") // Example: 61 is prime
} else {
    print("No.")
}



/*
run:

Yes, 78919 can be prime after deleting one digit.

*/

 



answered Jan 7 by avibootz

Related questions

...