3
\$\begingroup\$

I solved this prime number verifier problem:

import scala.io.StdIn

object Main extends App {
  val testCases = StdIn.readInt

  for (i <- 0 until testCases) {
    val limits = StdIn.readLine.split(" ")
    val m: Int = limits(0).toInt
    val n: Int = limits(1).toInt
    for (j <- m to n) {
      var prime = false
      if (isPrime(j))
        println(j)
    }
    println()
  }

  def isPrime(number: Int) : Boolean = {
    if (number == 1) 
      false
    else {
      for (h <- 2 to Math.sqrt(number).asInstanceOf[Int]) {
        if (number % h == 0 || number == 1) {
          return false
        }
      }
      true
    }
  }
}

I wrote the code this way because Scala doesn't have break statements, and return statements aren't very functional either. How do I go about writing this code in a more functional and idiomatic manner?

\$\endgroup\$
3
\$\begingroup\$

How about this?

def isPrime(n:Int):Boolean = n match {
  case 1 => false
  case 2 => true
  case 3 => true
  case 5 => true
  case 7 => true
  case n if (n%2==0 || n%3==0 || n%5==0 || n%7==0) => false
  case _ => (Stream.iterate(3, Math.sqrt(n).toInt+1){_ + 2} dropWhile((x:Int) => n%x != 0)).isEmpty
}

The code is straightforward. We know that the prime numbers below 10 are 2, 3, 5, 7. If a given number is the multiple of 2, 3, 5, or 7, is't not a prime. In other case (the last case branch) it generates stream from 3 to ceil(sqrt(n)) with step 2. We know that even numbers can't be a prime. And check that the argument is a multiple of any number in the stream. Basically the same logic with the original code. The reason I use Stream is to use lazy evaluation. With lazy evaluation, we can avoid unnecessary computation.

\$\endgroup\$
  • 1
    \$\begingroup\$ All the cases seem just premature optimization, the asker is very beginner and I fear you will only confuse him, Also I feel like generating the small divisors should be its own method. \$\endgroup\$ – Caridorc Aug 10 '15 at 14:12
  • 1
    \$\begingroup\$ @ntaibs, you really need to say at least something about the advantages of your code and what it does. \$\endgroup\$ – itsbruce Aug 11 '15 at 15:42
  • \$\begingroup\$ I think the stackoverflow gods want you to explain what makes this idiomatic, functional code? \$\endgroup\$ – j will Aug 11 '15 at 23:28
  • \$\begingroup\$ Where is the documentation for Stream.iterate? I found Stream.iterator but not Stream.iterate... \$\endgroup\$ – j will Aug 17 '15 at 3:10
  • \$\begingroup\$ 1.) The code does not compile at least on my system (Java8, Scala 2.11.7) 2.) Shouldn't it be .toInt instead of .asInstanceOf[Int] which is like a type cast? \$\endgroup\$ – user573215 Aug 20 '15 at 9:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.