title: Scala stream to find primes in specific interval
body: <p><strong>Problem:</strong></p>
  
  <p>I need to create a Scala program which uses Stream class and finds n-th prime number from interval [i, j] (whereas 1 &lt;= i &lt; j).</p>
  
  <p><strong>More information:</strong></p>
  
  <p>I am completely new in Scala but I've looked for various examples on how to find primes in Scala using Stream. None of them helped me to achieve my goal.</p>
  
  <p>I can't seem to understand how to make stream a finite list in interval [i, j] and how to take n-th prime number from that interval.</p>
  
  <p><strong>My code so far:</strong></p>
  
  <pre><code>def primeStream(args: Array[String], s: Stream[Int]): Stream[Int] =
          Stream.cons(s.head, primeStream(args,s.tail filter {_ % s.head != 0 }))
  
  if (args(0).toInt &lt; 1) {
          println("Entered parameter i does not meet requirements 1&lt;=i&lt;j (1&lt;=" + args(0) + "&lt;" + args(1) + ")")
          sys.exit(1)
  } else if (args(1).toInt &lt; args(0).toInt) {
          println("Entered parameter j does not meet requirements 1&lt;=i&lt;j (1&lt;=" + args(0) + "&lt;" + args(1) + ")")
          sys.exit(1)
  }
  
  val primes = primeStream(args,Stream.from(args(0).toInt)) // start from i element
  
  primes take args(1).toInt foreach println //Take j elements
  </code></pre>
  
  <p>Any help would be appreciated!</p>
  
  <p><strong>SOLUTION:</strong></p>
  
  <pre><code>def primeStream(s: Stream[Int]): Stream[Int] =
          Stream.cons(s.head, primeStream(s.tail filter {_ % s.head != 0 }))
  
  if (args(0).toInt &lt; 1) {
          println("Entered parameter i does not meet requirements 1&lt;=i&lt;j (1&lt;=" + args(0) + "&lt;" + args(1) + ")")
          sys.exit(1)
  } else if (args(1).toInt &lt; args(0).toInt) {
          println("Entered parameter j does not meet requirements 1&lt;=i&lt;j (1&lt;=" + args(0) + "&lt;" + args(1) + ")")
          sys.exit(1)
  } else if (args(0).toInt == 1) {
          println("1 is not a prime by definition!") 
          sys.exit(1)  // if args(0) is 1 then function hangs up - didn't come up with a better solution for this
  }
  
  val primes = primeStream(Stream.from(args(0).toInt)) // get primes starting from given parameter
  
  println(primes.takeWhile( _ &lt; args(1).toInt).take(args(2).toInt).last) // get n-th prime and print it out
  </code></pre>