Felipe
Felipe

Reputation: 7563

println inside forall at Scala

I have this function in Scala that check if the parameter is a prime number. How do I do to print only the first value of "d" that the function isPrime can divide by "n", inside de "(d => n % d != 0)"? I want to show the first value of "d" that says the "n" is not a prime number.

object Collection {
  def isPrime(n: Int): Boolean = (2 until n) forall (d => n % d != 0)

  def main(args: Array[String]): Unit = {
    println("isPrime(7): " + isPrime(7))
    println("isPrime(12): " + isPrime(12))
    println("isPrime(127): " + isPrime(127))
    println("isPrime(254): " + isPrime(254))
  }
}

Upvotes: 0

Views: 180

Answers (2)

Marcin
Marcin

Reputation: 454

What about this? You can invert question if number is not a prime.

def notPrime(n: Int) = (2 until n) find (d => n % d == 0)

As a result you get Option[Int] that can be easily checked for true/false. Negative answer "None" means it's a prime. Positive answer "Some" means it not a prime number.

notPrime(7): None
notPrime(12): Some(2)
notPrime(127): None
notPrime(254): Some(2)

Upvotes: 1

insan-e
insan-e

Reputation: 3921

Something like this maybe:

def isPrime(n: Int): Boolean = (2 until n) forall { d =>
  val remainder = n % d
  if (remainder == 0) println("Not prime because of" + d)
  remainder != 0
}

Upvotes: 2

Related Questions