Problem:
I need to create a Scala program which uses Stream class and finds n-th prime number from interval [i, j] (whereas 1 <= i < j).
More information:
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.
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.
My code so far:
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 < 1) {
println("Entered parameter i does not meet requirements 1<=i<j (1<=" + args(0) + "<" + args(1) + ")")
sys.exit(1)
} else if (args(1).toInt < args(0).toInt) {
println("Entered parameter j does not meet requirements 1<=i<j (1<=" + args(0) + "<" + 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
Any help would be appreciated!
SOLUTION:
def primeStream(s: Stream[Int]): Stream[Int] =
Stream.cons(s.head, primeStream(s.tail filter {_ % s.head != 0 }))
if (args(0).toInt < 1) {
println("Entered parameter i does not meet requirements 1<=i<j (1<=" + args(0) + "<" + args(1) + ")")
sys.exit(1)
} else if (args(1).toInt < args(0).toInt) {
println("Entered parameter j does not meet requirements 1<=i<j (1<=" + args(0) + "<" + 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( _ < args(1).toInt).take(args(2).toInt).last) // get n-th prime and print it out