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 Scala

2 Answers

0 votes
import scala.util.control.Breaks._

object Main extends App {
  def removeTheNDigit(num: Int, N: Int): Int = {
    val numStr = num.toString
    (numStr.take(N) + numStr.drop(N + 1)).toInt
  }

  def isPrime(n: Int): Boolean = {
    if (n < 2 || (n % 2 == 0 && n != 2)) {
      false
    } else {
      val count = Math.sqrt(n).toInt
      (3 to count by 2).forall(i => n % i != 0)
    }
  }

  val n = 78919
  val totalDigits = n.toString.length

  for (i <- 0 until totalDigits) {
    val tmp = removeTheNDigit(n, i)
    if (isPrime(tmp)) {
      println(s"yes number = $tmp")
      break
    }
  }
}



/*
run:

yes number = 7919

*/

 



answered Sep 28, 2024 by avibootz
0 votes
object PrimeChecker {
  def removeTheNDigit(num: Int, N: Int): Int = {
    val numStr = num.toString
    
    (numStr.take(N) + numStr.drop(N + 1)).toInt
  }

  def isPrime(n: Int): Boolean = {
    if (n < 2 || (n % 2 == 0 && n != 2)) {
      return false
    }

    val count = Math.sqrt(n).toInt
    for (i <- 3 to count by 2) {
      if (n % i == 0) {
        return false
      }
    }

    true
  }

  def main(args: Array[String]): Unit = {
    val n = 78919
    val totalDigits = n.toString.length

    for (i <- 0 until totalDigits) {
      val tmp = removeTheNDigit(n, i)
      if (isPrime(tmp)) {
        println(s"yes number = $tmp")
        return
      }
    }
  }
}


/*
run:

yes number = 7919

*/

 



answered Sep 28, 2024 by avibootz
edited Sep 28, 2024 by avibootz

Related questions

...