HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Prime number verifier

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
numberprimeverifier

Problem

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?

Solution

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.

Code Snippets

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
}

Context

StackExchange Code Review Q#100447, answer score: 3

Revisions (0)

No revisions yet.